Skip to content

Commit

Permalink
Always autoescape using minijinja
Browse files Browse the repository at this point in the history
  • Loading branch information
MikeMoolenaar committed Mar 20, 2024
1 parent 6f1849a commit a491552
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 10 deletions.
3 changes: 2 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use axum::{
};
use dotenv::dotenv;
use libsql::{Builder, Connection};
use minijinja::{path_loader, Environment};
use minijinja::{path_loader, AutoEscape, Environment};
use std::{env, net::SocketAddr, sync::Arc, time::Duration};
use tower::ServiceBuilder;
use tower_governor::{governor::GovernorConfigBuilder, GovernorLayer};
Expand Down Expand Up @@ -78,6 +78,7 @@ async fn main() {
let mut jinja = Environment::new();
jinja.set_loader(path_loader("templates"));
jinja.add_filter("date_string", date_string);
jinja.set_auto_escape_callback(|_| AutoEscape::Html);
let _ = SHARED_JINJA_ENV.set(jinja.clone());

// Setup static file service
Expand Down
17 changes: 10 additions & 7 deletions src/render_html.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,18 @@ pub fn render_block<S: Serialize>(template_name: &str, block_name: &str, context
}
}

// TODO: Improve error handling
pub fn render_html_str<S: Serialize>(template_raw: &str, context: S) -> Result<Html<String>, Box<dyn Error>> {
let template = SHARED_JINJA_ENV
pub fn render_str<S: Serialize>(template_raw: &str, context: S) -> Option<Html<String>> {
match SHARED_JINJA_ENV
.get()
.expect("Jinja environment not initialized!")
.render_str(template_raw, context)?;
// Minijiinja does not escape html when using render()
let str = v_htmlescape::escape(template.as_str());
return Ok(Html(str.to_string()));
.render_str(template_raw, context)
{
Ok(str) => Some(Html(str)),
Err(err) => {
println!("Error rendering string: {}", err);
return Html(String::from("Woopsie! Something broke!")).into();
}
}
}

fn render<S: Serialize>(
Expand Down
4 changes: 2 additions & 2 deletions src/routes/todos/create_todo.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::{
models::{todo_item::TodoItemRequest, user::User},
render_html::render_html_str,
render_html::render_str,
AppState,
};
use axum::{extract::State, http::StatusCode, response::Html, Form};
Expand Down Expand Up @@ -30,7 +30,7 @@ pub async fn create_todo(
return Err((StatusCode::INTERNAL_SERVER_ERROR, String::from("Unknown error")));
}

return Ok(render_html_str(
return Ok(render_str(
"Todo item '{{ title_clone }}' succesfuly added!",
context! {
title_clone
Expand Down

0 comments on commit a491552

Please sign in to comment.