laravel-template-engine
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
- Installation
- Quick start: an order email with an invoice
- Template syntax for the people editing templates
- Template types
- Recipients and languages
- Documents
- Notifications: SMS, Slack, Telegram and any channel
- Pictures and fonts
- Layouts
- Checking and saving
- Previews and test sends
- Building the editor yourself
- Moving templates between environments
- Your own filters
- The sandbox
- Events
- History of changes
- Configuration
- Roadmap
- Testing
- License
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,ccandbcchold recipient variables of its type, such ascustomer, and plain addresses, such asaccounting@example.com. - Every language. Each
toaddress gets its own email in its own language, falling back to the default language. - Locale-aware filters.
money,number,datewith month names, andplural, 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?".foronly over lists. Filters and their arguments. The formspluralneeds 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.
- Notification texts for any channel. SMS, Slack, and any channel a package adds, such as Telegram. People write the text; Laravel's notifications deliver it.
- Documents. The same templates render to HTML or PDF (with the
pdffeature), 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-defaultscreates 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 TemplateEngineServiceProvider;
configure
.with_providers
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 ;
use Serialize;
example returns data for previews and test sends, so people see a real order while editing.
defaults lists the templates the type comes with:
Create the default templates once, for example on deploy:
laravel template-engine:install-defaults
Send when the order is placed:
send.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
TemplateDatawithout a key. - Field types. Fields can be text, numbers,
bool, dates,Option<T>,Vec<T>, otherTemplateDatastructs andRecipient.- Dates: Laravel's
Timestamp,ZonedDateTime,civil::Dateandcivil::DateTime, or chrono's. serde_json::Valueis allowed too; the checks don't look inside it.
- Dates: Laravel's
- 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'sNone;Vec<Recipient>, which sends to everyone in it.
A template's to, cc and bcc list recipient variables and addresses:
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:
- that language exactly;
- the same language without its region (
ukforuk-UA); TEMPLATE_ENGINE_LOCALE;- 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 MailAttachment;
mail
.attach
.send
.await?;
To add a header to every email of a send, such as the one-click unsubscribe headers Gmail and Yahoo ask newsletters for:
mail
.header
.header
.send
.await?;
To send one template that people picked, such as this week's newsletter, instead of every active template of the type, pass its id. It is sent even if it isn't active, so a newsletter template can stay inactive and never go out by itself:
mail.template.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
Choosing the template:
named("...")picks one by name, andtemplate(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.
Notifications: SMS, Slack, Telegram and any channel
The package doesn't deliver notifications and isn't tied to any messenger. It writes the text, and your Laravel notification sends it over whatever channel your application has:
- Laravel's own
smsandslack; - a package channel, such as Telegram, Discord or push.
People manage the text of each channel in each language. Routing (phone numbers, chat IDs), queues and retries stay with Laravel.
A notification template is the text for one channel, chosen in its settings. The text is plain, not HTML, and may have a title, for channels such as push. Each type has at most one active template per channel, because a channel method returns one message.
Add the channels your application uses on top of sms and slack, so the editor can offer them
and the check can catch typos:
new.channel
Load the texts before sending, and render them in the notification's channel methods, which can't wait for the database:
use notification;
use NotificationTexts;
// Where the order ships:
let texts = notification.await?;
to.queue.await?;
How the methods behave:
text(channel, locale)gives the text in that language or the closest one. It fails withTemplateError::NoNotificationwhen no active template writes for the channel, which stops the notification.render(channel, locale)returnsNonein that case, along with the title and the language used.texts.channels()lists the channels that have a template, for achannelsmethod that sends only where someone wrote a text.
Pictures and fonts
Add the pictures templates may show, such as a logo or a signature, on the provider:
new
.image
.image
.font
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: anhttps://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:
new
.image
.layout
<!-- resources/layouts/brand.html -->
{{ content }}
{% if locale == "uk" %}ТОВ «Акме», Київ{% else %}Acme Ltd., Kyiv{% endif %}
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 ;
let input = mail
.content;
match create.await
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:
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_channel, duplicate_channel |
Notifications |
unknown_locale, unknown_type |
Languages and template types |
Previews and test sends
use ;
// An unsaved draft, rendered with the type's example data.
match preview.await? ;
// A saved email template, sent now to one address only, with "[Test] " before the subject.
send_test.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
isaccepts; - the cheat sheet.
A typical editor puts these together:
- the variable tree on the side, where a click inserts
{{ path }}(list items start fromitem, for use inside{% for item in ... %}); - autocompletion from the same paths and filters;
templates::checkas 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 callstemplates::send_test.
The model is laravel_template_engine::Template, so lists and deletes are ordinary queries:
let templates = query.filter.get.await?;
Moving templates between environments
People often prepare templates on staging and need the same ones in production. Export them to a file and import it on the other side:
laravel template-engine:export --path templates.json # every type
laravel template-engine:export --type order.placed --path order.json # one type
laravel template-engine:import templates.json --dry-run # what would change
laravel template-engine:import templates.json # create the missing ones
laravel template-engine:import templates.json --overwrite # replace existing ones too
How the import treats the file:
- Matching. A template is the same as an existing one when its type and name are.
- Existing templates. Without
--overwritethey are kept as they are, so edits made in production aren't lost. - Attached documents. They travel by name, because keys differ between environments.
- Checks. Every template is checked as an edit would be, and saved with
templates::create/update, so audit packages see the change. - Failures. A template with mistakes, or of a type this application doesn't have, is left out with the reasons, and the command exits with status 1.
transfer::export and transfer::import do the same from code, for buttons in an editor;
import returns an ImportReport with an Outcome per template.
Your own filters
Add filters on the provider. Templates may use them, and the checks know their arguments:
use ;
new.filter
.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,autoescapeor 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:
async
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 Updated;
async
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
- Next
- Global blocks people edit: company details, signature, footer.
- Layouts and branding per tenant.
- Highlighting the conditions that matched in previews.
- Word (DOCX) documents, once a crate converts HTML to DOCX.
- Typst documents through
typst-laravel.
- Later
- 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
- Apache License, Version 2.0 (LICENSE-APACHE)
- MIT license (LICENSE-MIT)
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.