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

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").
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.