Basic run with tera templating

Signed-off-by: baalajimaestro <me@baalajimaestro.me>
This commit is contained in:
baalajimaestro 2022-11-11 20:01:58 +05:30
parent 0bdf93d737
commit db32d8b07e
Signed by: baalajimaestro
GPG key ID: F93C394FE9BBAFD5
3 changed files with 40 additions and 14 deletions

View file

@ -1,26 +1,36 @@
use actix_web::{get, post, web, App, HttpResponse, HttpServer, Responder};
use actix_web::{get, App, HttpResponse, HttpServer, Responder, web::{Data}};
use tera::{Tera, Context};
#[get("/")]
async fn hello() -> impl Responder {
HttpResponse::Ok().body("Hello world!")
struct Template {
paste: Tera,
}
#[post("/echo")]
async fn echo(req_body: String) -> impl Responder {
HttpResponse::Ok().body(req_body)
}
async fn manual_hello() -> impl Responder {
HttpResponse::Ok().body("Hey there!")
#[get("/{paste_id}")]
async fn paste_render(data: Data<Template>) -> impl Responder {
let my_data = data.get_ref();
let mut context = Context::new();
context.insert("paste_id", "owo");
let rendered = my_data.paste.render("paste.html", &context);
HttpResponse::Ok().body(rendered.unwrap())
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
let tera = match Tera::new("templates/*.html") {
Ok(t) => t,
Err(e) => {
println!("Parsing error(s): {}", e);
::std::process::exit(1);
}
};
let data = Data::new(Template { paste: tera });
HttpServer::new(move || {
App::new()
.service(hello)
.service(echo)
.route("/hey", web::get().to(manual_hello))
.app_data(Data::clone(&data))
.service(paste_render)
})
.bind(("127.0.0.1", 8080))?
.run()

11
templates/base.html Normal file
View file

@ -0,0 +1,11 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Actix Web</title>
</head>
<body>
{% block content %}
{% endblock content %}
</body>
</html>

5
templates/paste.html Normal file
View file

@ -0,0 +1,5 @@
{% extends "base.html" %}
{% block content %}
<h1>This is {{paste_id}}</h1>
{% endblock content %}