Template Engine Implementation in Rust
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Template Engine runs in O(n) time and O(n) space, in Rust as in every other language.
- ✓`std::borrow::Cow<str>` is the type this problem was designed around: the escaper returns `Borrowed` when nothing needed changing and `Owned` otherwise, so clean values never allocate.
- ✓Return `Cow<'_, str>` from the escaper and let the caller decide. A reviewer who sees `-> String` will ask why every clean field allocates.
- ✓The Rust trap: The natural design is `enum Op<'a> { Lit(&'a str), Var(&'a str) }` borrowing from the template text, and it is lovely until you try to cache it.
- ✓Every call here is statically dispatched, so the escaper inlines into the render loop and the measurable costs are allocation and UTF-8 checking.
What Template Engine actually is
Template Engine in Rust: what you actually reach for
Rust implementation
use std::{borrow::Cow, collections::HashMap, ops::Range};
// Byte ranges, not &str slices: a plan that borrowed from its own source
// text would be a self-referential struct, which cannot be moved or cached.
enum Op { Lit(Range<usize>), Var { hole: Range<usize>, raw: bool } }
pub struct Template { src: String, ops: Vec<Op> }
fn escape(s: &str) -> Cow<'_, str> {
// No special byte means no allocation at all: the borrowed arm is the hot one.
if !s.bytes().any(|b| matches!(b, b'&' | b'<' | b'>' | b'"')) { return Cow::Borrowed(s); }
let mut out = String::with_capacity(s.len() + 16);
for c in s.chars() {
let ent = match c { '&' => "&", '<' => "<", '>' => ">", '"' => """, _ => "" };
if ent.is_empty() { out.push(c) } else { out.push_str(ent) }
}
Cow::Owned(out)
}
impl Template {
pub fn compile(src: String) -> Self {
let (mut ops, mut pos) = (Vec::new(), 0usize);
while let Some(off) = src[pos..].find("{{") {
let open = pos + off;
let Some(len) = src[open + 2..].find("}}") else { break };
let close = open + 2 + len;
if open > pos { ops.push(Op::Lit(pos..open)); }
let hole = open + 2..close;
ops.push(Op::Var { raw: src[hole.clone()].trim_start().starts_with('&'), hole });
pos = close + 2;
}
if pos < src.len() { ops.push(Op::Lit(pos..src.len())); }
Template { src, ops }
}
pub fn render(&self, ctx: &HashMap<&str, &str>) -> String {
let mut out = String::with_capacity(self.src.len() * 2); // one alloc, then push_str
for op in &self.ops {
match op {
Op::Lit(r) => out.push_str(&self.src[r.clone()]),
Op::Var { hole, raw } => {
let k = self.src[hole.clone()].trim_matches(|c: char| c.is_whitespace() || c == '&');
let v = ctx.get(k).copied().unwrap_or("");
if *raw { out.push_str(v) } else { out.push_str(&escape(v)) }
}
}
}
out
}
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Rust-specific trap
Performance in Rust, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Rust type or library should I use for Template Engine?
`std::borrow::Cow<str>` is the type this problem was designed around: the escaper returns `Borrowed` when nothing needed changing and `Owned` otherwise, so clean values never allocate. `std::fmt::Write` with `write!` gives a sink-agnostic renderer, `String::with_capacity` sizes the buffer, and `std::ops::Range<usize>` is what a compiled plan stores instead of slices. The ecosystem splits on when it compiles: `askama` is a derive macro that turns the template into Rust code at build time with field names checked by the compiler, while `minijinja` and `tera` parse at run time.
What is the most common Rust mistake when implementing Template Engine?
The natural design is `enum Op<'a> { Lit(&'a str), Var(&'a str) }` borrowing from the template text, and it is lovely until you try to cache it. A cache entry must own the source and the plan together, which makes the struct self-referential: `compile(src: String) -> Template` would return a value whose `ops` borrow from its own `src` field, and moving the struct moves `src`, invalidating every slice into it. The compiler refuses with E0515, 'cannot return value referencing local variable'. Leaking the source with `Box::leak` compiles, and leaks a megabyte per hot reload. Store byte offsets.
How does Template Engine actually perform in Rust?
Every call here is statically dispatched, so the escaper inlines into the render loop and the measurable costs are allocation and UTF-8 checking. A `Cow::Borrowed` on a clean field is genuinely free. Sizing the output with `String::with_capacity` avoids the doubling reallocations that dominate a naive render, since each growth memcpys everything written so far. Indexing `self.src[range]` costs a bounds check plus a character-boundary check that panics on a mid-codepoint offset, so build ranges only from offsets the lexer produced. Dropping a plan is one `Vec` free: no tracing pass, no finaliser, no cache eviction thread. Time complexity is O(n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialBefore paying for GitHub Copilot, check its student and free-tier options on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.