Add ability to render templates
All checks were successful
Cargo Build & Test / Tests (pull_request) Successful in 12s
Cargo Build & Test / Test publish (pull_request) Successful in 12s
Cargo Build & Test / check-cargo-version (pull_request) Successful in 6s

This commit is contained in:
Jan Gleytenhoover 2024-08-20 22:40:04 +02:00
parent aaa062db31
commit a392734d59
3 changed files with 19 additions and 0 deletions

@ -1,3 +1,4 @@
pub mod router;
pub mod entities;
pub mod utilities;
pub mod template;

5
src/template.rs Normal file

@ -0,0 +1,5 @@
use maud::Markup;
pub trait Template {
fn render(&self) -> Markup;
}

@ -2,6 +2,8 @@ use ascii::AsciiString;
use maud::Markup;
use tiny_http::{Header, Request, Response};
use crate::template::Template;
/// Returns a 404 response
pub fn respond_not_found(request: Request) {
let response = Response::from_string("Not Found").with_status_code(404);
@ -9,6 +11,17 @@ pub fn respond_not_found(request: Request) {
let _ = request.respond(response);
}
/// Renders a template
pub fn respond_template(request: Request, template: impl Template) {
let response = Response::from_string(template.render())
.with_header(Header {
field: "Content-Type".parse().unwrap(),
value: AsciiString::from_ascii("text/html; charset=utf8").unwrap(),
});
let _ = request.respond(response);
}
/// Renders html
pub fn respond_html(request: Request, content: Markup) {
let response = Response::from_string(content);