laravel-template-engine 0.2.0

Templates for emails, documents and notifications that your team edits, stored in the database
Documentation

laravel-template-engine

Crates.io Docs.rs CI License: MIT OR Apache-2.0

Templates for emails, documents and notifications that your team edits, stored in the database, for Laravel Rust.

Your code declares a template type, such as order.placed, with its data. Everything else lives in the database, and the people who run the business change it without a deploy:

  • the text, in every language;
  • the subject and the sender;
  • who gets the email, with copies and hidden copies.

A type can have several active templates, and all of them are sent: one email to the customer and another to accounting. The same engine makes documents, such as invoices and contracts, as HTML or PDF, and attaches them to emails.

The package is the backend only. It gives an editor everything it needs: the variables of each type as JSON, checks with line numbers and "did you mean" hints, previews and test sends. You draw the editor with whatever your application uses.

Features

  • One derive, no registration. #[derive(TemplateData)] describes a type and its variables, and the engine finds it on its own. There's no config file and no list of types.
  • Recipients in the database. A template's to, cc and bcc hold recipient variables of its type, such as customer, and plain addresses, such as accounting@example.com.
  • Every language. Each to address gets its own email in its own language, falling back to the default language.
  • Locale-aware filters. money, number, date with month names, and plural, all using CLDR data through ICU4X.
  • A real sandbox. Templates see only their type's data and a short list of filters. They can't call code, read files or include other templates. Every render has limits on work, output size, nesting and time.
  • Checks before saving. Syntax errors with the line and column. Unknown variables with "did you mean order.number?". for only over lists. Filters and their arguments. The forms plural needs for each language. The settings.
  • Emails through the queue. Each email is rendered in the worker, so it uses the template as it is when the email goes out. CSS is inlined for email clients, and the plain text version is made for you.
  • Documents. The same templates render to HTML or PDF (with the pdf feature), for download or as attachments.
  • An editor API. The variable tree as JSON, the filters, a syntax cheat sheet, previews with example data, and test sends to one address.
  • Defaults from code. laravel template-engine:install-defaults creates the templates your types come with and never overwrites the changes people made.
  • Events for rendering, sending and failures. A listener writes a send log if you need one.

Installation

cargo add laravel-template-engine --features pdf

Leave out pdf if you only need emails and HTML documents.

Register the provider in src/app.rs:

use laravel_template_engine::TemplateEngineServiceProvider;

Application::configure()
    .with_providers(|providers| {
        providers.add(TemplateEngineServiceProvider::new());
    })

Then create the table:

laravel migrate

The migration creates template_engine_templates. If a table with that name already exists, the migration stops with a message saying so, and changes nothing.

Quick start: an order email with an invoice

Declare the type where the event happens. Its fields are the variables templates use:

use laravel_template_engine::{DefaultTemplate, Recipient, TemplateData};
use serde::Serialize;

#[derive(Serialize, TemplateData)]
#[template(
    key = "order.placed",
    description = "A customer placed an order",
    example = OrderPlaced::example,
    defaults = OrderPlaced::defaults,
)]
pub struct OrderPlaced {
    #[template(description = "The customer")]
    pub customer: Recipient,
    #[template(description = "The order")]
    pub order: Order,
}

#[derive(Serialize, TemplateData)]
pub struct Order {
    #[template(description = "Order number")]
    pub number: String,
    #[template(description = "Courier or pickup")]
    pub delivery: String,
    #[template(description = "Total")]
    pub total: f64,
    #[template(description = "When it was placed")]
    pub placed_at: laravel::time::Timestamp,
    #[template(description = "What was ordered")]
    pub items: Vec<Item>,
}

#[derive(Serialize, TemplateData)]
pub struct Item {
    #[template(description = "Product")]
    pub name: String,
    #[template(description = "How many")]
    pub quantity: u32,
    #[template(description = "Price of one")]
    pub price: f64,
}

example returns data for previews and test sends, so people see a real order while editing. defaults lists the templates the type comes with:

impl OrderPlaced {
    fn example() -> Self {
        Self {
            customer: Recipient::new("olena@example.com").name("Olena").locale("uk"),
            order: Order {
                number: "1042".into(),
                delivery: "courier".into(),
                total: 1250.5,
                placed_at: "2026-12-03T10:15:00Z".parse().unwrap(),
                items: vec![Item { name: "Lamp".into(), quantity: 2, price: 625.25 }],
            },
        }
    }

    fn defaults() -> Vec<DefaultTemplate> {
        vec![
            DefaultTemplate::document("Invoice")
                .content("en", "", include_str!("../resources/templates/invoice.en.html"))
                .content("uk", "", include_str!("../resources/templates/invoice.uk.html"))
                .filename("invoice-{{ order.number }}"),
            DefaultTemplate::mail("Confirmation")
                .content("en", "Order {{ order.number }}", "<p>Thank you, {{ customer.name }}!</p>")
                .content("uk", "Замовлення {{ order.number }}", "<p>Дякуємо, {{ customer.name }}!</p>")
                .to(["customer"])
                .cc(["Accounting <accounting@example.com>"])
                .attach_document("Invoice"),
        ]
    }
}

Create the default templates once, for example on deploy:

laravel template-engine:install-defaults

Send when the order is placed:

laravel_template_engine::send(OrderPlaced { customer, order }).await?;

Olena gets the Ukrainian email with the invoice attached as a PDF, and accounting gets a copy. From now on, a manager can do all of this without a deploy:

  • change the text;
  • add an English version;
  • send accounting a separate email of their own;
  • stop the copy.

Template syntax for the people editing templates

The syntax is MiniJinja's, which is Jinja's. This is all a manager needs. The editor API serves the same sheet as editor::CHEAT_SHEET:

You want to Write
Insert a value {{ customer.name }}
Show something only sometimes {% if order.delivery == "courier" %} … {% else %} … {% endif %}
Check that a value is there {% if customer.phone %} … {% endif %}
Repeat for each item of a list {% for item in order.items %} {{ item.name }} {% endfor %}
Number the items {{ loop.index }}, and loop.first, loop.last
Show text when a list is empty {% for item in order.items %} … {% else %} No items {% endfor %}
A fallback for a missing value {{ customer.phone | default("—") }}
An amount with its currency {{ order.total | money("UAH") }} → 1 250,50 ₴
A number {{ order.weight | number(2) }} → 1 250,50
A date {{ order.placed_at | date("%d.%m.%Y") }} → 03.12.2026
A date with the month's name {{ order.placed_at | date("%d %B %Y") }} → 03 грудня 2026
The right word for a number {{ count }} {{ count | plural("товар", "товари", "товарів") }}
Change case {{ name | upper }}, {{ name | lower }}, {{ name | title }}
Count a list's items {{ order.items | length }}
A picture the developers added <img src="logo" alt="Acme">
A note only for you {# this text is not sent #}

plural takes one form for each of the language's plural categories. English has two ("item", "items"), and Ukrainian and Polish have three ("товар", "товари", "товарів"). The check says how many a language needs.

money, number, date and plural follow the language of the text being rendered. For example, money("UAH") gives 1 250,50 ₴ in Ukrainian and UAH 1,250.50 in English.

The other filters are:

  • trim, replace, capitalize, round, abs, int, float, string;
  • first, last, join, sort, reverse, sum, min, max, unique.

is accepts defined, none, odd, even, divisibleby, number, string, startingwith and endingwith.

Template types

A template type is a struct with #[derive(Serialize, TemplateData)] and #[template(key = "...", example = ...)].

  • Nested data. Structs inside it derive TemplateData without a key.
  • Field types. Fields can be text, numbers, bool, dates, Option<T>, Vec<T>, other TemplateData structs and Recipient.
    • Dates: Laravel's Timestamp, ZonedDateTime, civil::Date and civil::DateTime, or chrono's.
    • serde_json::Value is allowed too; the checks don't look inside it.
  • Names. #[serde(rename)] and #[serde(skip)] are respected, so templates see the names your JSON has.
  • Descriptions. #[template(description = "...")] is shown to the people editing templates.
Struct attribute Meaning
key = "order.placed" The type's key. With it, the struct is a template type the engine finds on its own
description = "..." What the type is for
example = path::to::fn Required with key: fn() -> Self, the data of previews and test sends
defaults = path::to::fn Optional: fn() -> Vec<DefaultTemplate>, for template-engine:install-defaults

laravel_template_engine::types() lists the types, and find_type("order.placed") finds one.

Recipients and languages

These fields of a type are its recipient variables:

  • Recipient;
  • Option<Recipient>, skipped when it's None;
  • Vec<Recipient>, which sends to everyone in it.

A template's to, cc and bcc list recipient variables and addresses:

{ "to": ["customer", "manager"], "cc": ["Accounting <accounting@example.com>"], "bcc": [] }

One email per to address. Every address in to gets an email of its own, so customers never see each other's addresses. The cc and bcc addresses get a copy of each.

Language. Each email is in its recipient's language (Recipient::locale), chosen in this order:

  1. that language exactly;
  2. the same language without its region (uk for uk-UA);
  3. TEMPLATE_ENGINE_LOCALE;
  4. the first language the template has.

Addresses written into the template have no language of their own, so they get the default.

To attach files of your own to every email of a send:

use laravel_template_engine::MailAttachment;

laravel_template_engine::mail(order)
    .attach(MailAttachment::storage("terms/2026.pdf"))
    .send()
    .await?;

Documents

A document template has the same text by language, and these settings:

Setting Values
format pdf (with the pdf feature) or html
paper a4 (default), a3, a5, a6, letter, legal, …
orientation portrait or landscape
filename A template itself, such as invoice-{{ order.number }}; the extension is added
layout A layout the text goes into
margins {"top": 15, "right": 15, "bottom": 15, "left": 15}, in millimeters, for PDFs
font_family, font_size, line_height The text's font, its size in points and the line spacing, such as "Times New Roman", 12, 1.15

The font, size and spacing go into a <style> block at the top, so people don't repeat them in every template. A template's own CSS still wins.

Render one for a download:

pub async fn invoice(Params(id): Params<i64>) -> laravel::Result<laravel::http::Download> {
    let order = load_order(id).await?;
    let invoice = laravel_template_engine::document(&order).named("Invoice").locale("uk").render().await?;
    Ok(invoice.into_download())
}

Choosing the template:

  • named("...") picks one by name, and template(id) picks one by key.
  • When a type has exactly one active document template, neither is needed.
  • To attach a document to an email, the email template lists the document's key in attach_documents.

PDFs are made by printpdf in pure Rust, with 15 mm margins. There's no browser to install and nothing to run on the server. Keep document HTML simple and table-based, as for dompdf. Text in any script works: the font is embedded in the PDF.

Pictures and fonts

Add the pictures templates may show, such as a logo or a signature, on the provider:

TemplateEngineServiceProvider::new()
    .image("logo", include_bytes!("../resources/images/logo.png").to_vec())
    .image("signature", include_bytes!("../resources/images/signature.png").to_vec())
    .font("Inter", include_bytes!("../resources/fonts/Inter-Regular.ttf").to_vec())

A template shows a picture by its name, <img src="logo" alt="Acme" style="width: 40mm">. The engine handles the rest by where it goes:

Where How the picture gets there
Emails Attached to the email and shown inline (cid:logo), because Gmail and Outlook don't show data: pictures
PDF documents Drawn into the PDF
HTML documents and previews As a data: URI, so a browser shows it

Pictures can be PNG, JPEG or GIF. A template may also use data:image/...;base64,... pictures directly. Emails and HTML documents may use https:// pictures, which the reader's mail client or browser loads. PDFs never load anything from the internet or from the server's files: they show registered pictures and data: pictures only, even when a src comes from the data.

The check refuses a picture that won't show, and suggests the closest name:

  • unknown_image: There's no picture "lgo". Did you mean "logo"?;
  • remote_image: an https:// picture in a PDF.

editor::schema() lists the pictures and fonts, so an editor can offer them.

Fonts are for PDFs: font-family: Inter uses the font registered as Inter. Without one, PDFs use a system font, or the renderer's own when the server has none.

Layouts

A layout is the part every email or document shares: the header with the logo, the footer with the company's details, the styles. Developers add layouts in code, and a template chooses one in its settings ("layout": "brand"). People then write only the text:

TemplateEngineServiceProvider::new()
    .image("logo", include_bytes!("../resources/images/logo.png").to_vec())
    .layout("brand", include_str!("../resources/layouts/brand.html"))
<!-- resources/layouts/brand.html -->
<style>
  .header { border-bottom: 2px solid #0a6; padding-bottom: 8px }
  .footer { color: #777; font-size: 12px }
</style>
<div class="header"><img src="logo" alt="Acme" style="width: 40mm"></div>
{{ content }}
<div class="footer">
  {% if locale == "uk" %}ТОВ «Акме», Київ{% else %}Acme Ltd., Kyiv{% endif %}
</div>

A layout sees three variables:

  • content: the template's HTML;
  • subject: the email's subject, empty for documents;
  • locale: the language of the text.

Layouts render in the same sandbox as templates, and their CSS is inlined into emails like the templates' own. A layout that doesn't parse, or doesn't show {{ content }}, stops the application at startup. A template that names a layout that doesn't exist fails the check with unknown_layout and the closest name. editor::schema() lists the layouts.

Checking and saving

Write templates through templates::create and templates::update. They check the template first and refuse it with TemplateError::Invalid and a list of issues:

use laravel_template_engine::{TemplateError, TemplateInput, templates};

let input = TemplateInput::mail("order.placed", "Confirmation")
    .content("en", "Order {{ order.numbr }}", "<p>Thank you!</p>");

match templates::create(input).await {
    Ok(template) => { /* saved */ }
    Err(error) => {
        for issue in error.downcast_ref::<TemplateError>().map(TemplateError::issues).unwrap_or_default() {
            // content.en.subject (line 1): There's no `order.numbr`. Did you mean `order.number`?
            println!("{issue}");
        }
    }
}

templates::check(&input) returns the same issues without saving, so an editor can check while someone types. Each Issue serializes to JSON for the UI:

{
  "field": "content.en.subject",
  "line": 1,
  "column": 10,
  "code": "unknown_variable",
  "message": "There's no `order.numbr`. Did you mean `order.number`?",
  "suggestion": "order.number"
}

The codes are:

Codes What they cover
syntax The template doesn't parse
unknown_variable, not_a_list Variables that don't exist, and for over something that isn't a list
unknown_filter, filter_arguments, filter_input, plural_forms Filters and how they're used
unknown_test, forbidden_call, forbidden_tag What templates may and may not do
too_deep, too_long Nesting and length limits
required Missing names, text or recipients
unknown_recipient, invalid_address Recipients
unknown_document, invalid_paper, pdf_disabled, out_of_range, invalid_font Documents
unknown_image, remote_image, unknown_layout Pictures and layouts
unknown_locale, unknown_type Languages and template types

Previews and test sends

use laravel_template_engine::templates::{self, Preview};

// An unsaved draft, rendered with the type's example data.
match templates::preview(&input, Some("uk")).await? {
    Preview::Mail(mail) => (mail.subject, mail.html, mail.text),
    Preview::Document(document) => /* document.html, or document.bytes for the PDF */,
};

// A saved email template, sent now to one address only, with "[Test] " before the subject.
templates::send_test(template.id, "me@example.com", Some("uk")).await?;

Building the editor yourself

editor::schema() returns everything an editor needs, as JSON:

  • every type with its variable tree, its recipient variables and its example data;
  • every filter with its arguments, your own included;
  • the tests is accepts;
  • the cheat sheet.
{
  "types": [{
    "key": "order.placed",
    "description": "A customer placed an order",
    "recipients": ["customer"],
    "variables": [
      { "name": "customer", "path": "customer", "type": "recipient", "description": "The customer", "optional": false,
        "fields": [{ "name": "email", "path": "customer.email", "type": "text" }, "..."] },
      { "name": "order", "path": "order", "type": "object", "fields": [
        { "name": "items", "path": "order.items", "type": "list",
          "item": { "type": "object", "fields": [{ "name": "name", "path": "item.name", "type": "text" }, "..."] } },
        "..."
      ] }
    ],
    "example": { "customer": { "email": "olena@example.com" }, "order": { "number": "1042" } }
  }],
  "filters": [{ "name": "money", "description": "...", "example": "{{ order.total | money(\"UAH\") }}",
                "args": [{ "name": "currency", "type": "text", "required": false }] }],
  "tests": ["defined", "none"],
  "cheat_sheet": "# Template syntax ..."
}

A typical editor puts these together:

  • the variable tree on the side, where a click inserts {{ path }} (list items start from item, for use inside {% for item in ... %});
  • autocompletion from the same paths and filters;
  • templates::check as people type, with the issues shown next to their fields;
  • a preview pane fed by templates::preview, and a "send me a test" button that calls templates::send_test.

The model is laravel_template_engine::Template, so lists and deletes are ordinary queries:

let templates = Template::query().filter(Template::type_key.eq("order.placed")).get().await?;

Your own filters

Add filters on the provider. Templates may use them, and the checks know their arguments:

use laravel_template_engine::{ArgKind, Filter, TemplateEngineServiceProvider, Value};

TemplateEngineServiceProvider::new().filter(
    Filter::new("phone", "A phone number with spaces", |value: Value, _args: &[Value]| {
        Ok(Value::from(format_phone(&value.to_string())))
    })
    .example("{{ customer.phone | phone }}"),
)

.arg("name", ArgKind::Text, required) declares each argument.

The sandbox

Templates render in a MiniJinja environment of their own, not the application's views.

What templates can reach:

  • only their type's data, the filters above and range (at most 10,000 numbers);
  • no functions, globals, methods, files or network;
  • no include, import, extends, macro, call, autoescape or recursive loops.

Values are HTML-escaped in bodies, so data can't change an email's markup.

Every render has limits:

Limit Default Setting
Work, roughly steps and loop iterations 2,000,000 TEMPLATE_ENGINE_FUEL
Output 2 MiB TEMPLATE_ENGINE_MAX_OUTPUT
Time 2 s TEMPLATE_ENGINE_TIMEOUT_MS
Nesting of if and for 10 TEMPLATE_ENGINE_MAX_DEPTH
Length of a template's text 200,000 characters TEMPLATE_ENGINE_MAX_LENGTH

A render that runs past a limit fails with a message saying which limit.

Events

Event When
TemplateRendered A template rendered: for an email, a document, a preview or a test send
TemplateMessageSent An email went to the mailer
TemplateMessageFailed An email couldn't be rendered or sent

Each event carries template_id, type_key, kind, locale, recipient, and error on failures.

What happens on a failure:

  • When the mailer fails, the queue tries again (three attempts), and every failed attempt dispatches the event.
  • A template that doesn't render isn't tried again.

There's no send log in the package. A listener writes one if you need it:

#[listener]
async fn log_failed(event: Event<TemplateMessageFailed>) -> laravel::Result<()> {
    tracing::warn!(template = event.template_id, to = %event.recipient, "{}", event.error);
    Ok(())
}

History of changes

The package has no versions or history of its own. Template is an ordinary Laravel Rust model, so saving one dispatches Created<Template>, Updated<Template> (with the changed columns) and Deleted<Template>. An audit or activity log package listens to these model events to record who changed what. You can also write the listener yourself:

use laravel::model::Updated;

#[listener]
async fn audit(event: Event<Updated<Template>>) -> laravel::Result<()> {
    for change in event.changes.iter() {
        // change.column, change.old, change.new
    }
    Ok(())
}

Configuration

Every setting has a default, so nothing needs to be set:

Variable Default Meaning
TEMPLATE_ENGINE_LOCALE en The language used when a recipient's language has no text
TEMPLATE_ENGINE_CURRENCY USD The currency of money without an argument
TEMPLATE_ENGINE_QUEUE_CONNECTION the default The queue connection emails go through
TEMPLATE_ENGINE_QUEUE the default The queue emails go on
TEMPLATE_ENGINE_TEST_PREFIX [Test] What a test send puts before the subject

The limits are in The sandbox.

Change settings in code with config.section_mut::<TemplateEngineConfig>() in with_config.

Roadmap

  • 0.3
    • Global blocks people edit: company details, signature, footer.
    • Layouts and branding per tenant.
    • Exporting and importing templates between environments.
    • Highlighting the conditions that matched in previews.
    • Word (DOCX) documents, once a crate converts HTML to DOCX.
    • Typst documents through typst-laravel.
  • 0.4
    • SMS, Telegram and push channels through Laravel Rust's notification channels.
    • Unsubscribing by message type.

Testing

Tests run on SQLite in memory:

docker run --rm -v "$PWD":/app -w /app rust:1.99 cargo test --features sqlite,pdf

PostgreSQL and MySQL run from docker-compose.yml:

docker compose up -d
docker run --rm --network host -v "$PWD":/app -w /app \
    -e TEMPLATE_ENGINE_TEST_POSTGRES_URL=postgres://postgres:secret@127.0.0.1:55432/postgres \
    -e TEMPLATE_ENGINE_TEST_MYSQL_URL=mysql://root:secret@127.0.0.1:53306/templates \
    rust:1.99 cargo test --features postgres,mysql,pdf

License

Licensed under either of

at your option.

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this crate by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.