Available on crate feature
tera only.Expand description
Tera HTML template engine integration.
Requires features = ["tera"].
§Quick start
- Put templates in
templates/(e.g.templates/index.html). - Call
init(orinit_from_env) once at startup. - Call
renderfrom 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 templatesOnly 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.
- Tera
Engine - 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
.awaitpoints 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"). - reload
- Reload the global template engine’s templates from disk.
- render
- Render
template_namewithctxusing the global engine and return a200 OKHTML response.