Skip to main content

Module template

Module template 

Source
Available on crate feature tera only.
Expand description

Tera HTML template engine integration.

Requires features = ["tera"].

§Quick start

  1. Put templates in templates/ (e.g. templates/index.html).
  2. Call init (or init_from_env) once at startup.
  3. Call render from any handler.
use rust_web_server::template::{self, Context};

// At startup:
template::init("templates").unwrap();

// In a handler:
let mut ctx = Context::new();
ctx.insert("title", "Home");
ctx.insert("items", &["Rust", "rws", "Tera"]);
let response = template::render("index.html", &ctx).unwrap();

Templates use Jinja2 syntax: {{ variable }}, {% if cond %}, {% for item in list %}, {% extends "base.html" %}.

§Hot reload

Edit a template file and it’s re-read from disk on the next reload — no server restart, unlike a code change. reload is wired into the same SIGHUP hook (crate::config_reload::reload) used for CORS, rate limits, and TLS certs, so kill -HUP $(pidof rws) — or your own trigger calling config_reload::reload() — picks up edited templates too:

use rust_web_server::template;

template::init("templates").unwrap();
// ... edit templates/index.html on disk ...
template::reload().unwrap(); // re-globs the directory, replacing all templates

§View helpers (18.35.0)

Every engine has these functions:

  • url_for(name="posts.show", id=7) — the path of a named route (router::url_for); arguments the pattern doesn’t have become the query string. Its output is percent-encoded, so | safe is fine (Tera otherwise writes / as /, which browsers read back as /).
  • vite(entry="src/main.ts") — the <script>/<link> tags of a Vite entry from the installed vite helper (| safe).
  • vite_asset(path="src/logo.svg") — a built asset’s URL (| safe).

page_context starts a Context for a request with its flash messages (flash, notice, alert), the CSRF token (csrf_token, and csrf_field, a hidden _csrf input: {{ csrf_field | safe }}) and the request path (path):

use rust_web_server::template::{page_context, TeraEngine};

let engine = TeraEngine::from_raw(&[("form.html", r#"<form method="post" action="{{ url_for(name='doc_form_save') | safe }}">{{ csrf_field | safe }}</form>"#)]).unwrap();
rust_web_server::router::name_route("doc_form_save", "/save");
let html = engine.render("form.html", &page_context(&request)).unwrap();
assert!(html.starts_with(r#"<form method="post" action="/save">"#));

Only engines created from a glob (init, init_from_env, TeraEngine::from_dir, TeraEngine::from_glob) can reload — an engine built from TeraEngine::from_raw has no directory to re-read, so TeraEngine::reload returns Err for it.

Structs§

Context
The struct that holds the context of a template rendering.
TeraEngine
A Tera template engine instance.

Enums§

Value
Represents any valid JSON value.

Functions§

global
Acquire a read lock on the global template engine. Held only for the duration of one render — never store the guard across .await points or requests.
init
Initialize the global template engine from a directory on disk.
init_from_env
Initialize the global engine from RWS_CONFIG_TEMPLATE_DIR (default: "templates").
page_context
A Context for rendering a page in answer to request: flash (a list of {kind, text}), notice and alert (the first of each, when there is one), csrf_token and csrf_field (csrf feature; from CsrfLayer, else its _csrf cookie; empty without either) and path.
reload
Reload the global template engine’s templates from disk.
render
Render template_name with ctx using the global engine and return a 200 OK HTML response.
try_global
A read lock on the global engine, or None before init (18.35.0).