Text and HTML templates

suggest change

A template is text with holes in it: a fixed layout plus placeholders that get filled with data at run time. You use one for HTML pages, emails, reports, config files and generated code.

Dart has no template engine in the SDK, but you often don't need one. String interpolation handles a lot, and dart:convert has HtmlEscape for making text safe to put in HTML. When templates should live in separate files, be edited by non-programmers, or be shared with other languages, use a package. mustache_template is the most widely used. jinja is a port of Python's Jinja2 that adds template inheritance and filters.

This article covers:

The examples were run with Dart 3.13, mustache_template 2.0.6, jinja 0.7.2 and shelf 1.4.3.

String interpolation as a template

A function that takes data and returns a string built with interpolation is a template. It's type-checked, fast, and needs no package. Multi-line strings (''') keep the layout readable, and a collection for inside ${...} handles repeated parts:

class Item {
  final String name;
  final int qty;
  final double price;
  const Item(this.name, this.qty, this.price);
  double get total => qty * price;
}

String invoice(String customer, List<Item> items) {
  final total = items.fold(0.0, (sum, i) => sum + i.total);
  return '''
Invoice for $customer
${'-' * 36}
${[for (final i in items) '${i.name.padRight(20)}${i.qty.toString().padLeft(4)}${i.total.toStringAsFixed(2).padLeft(12)}'].join('\n')}
${'-' * 36}
${'Total'.padRight(24)}${total.toStringAsFixed(2).padLeft(12)}
${items.length > 2 ? 'Thank you for the large order!' : 'Thank you!'}''';
}

void main() {
  print(invoice('ACME Corp', const [
    Item('Widget', 3, 2.5),
    Item('Gadget', 1, 19.99),
    Item('Thingamajig', 10, 0.75),
  ]));
}

Output:

Invoice for ACME Corp
------------------------------------
Widget                 3        7.50
Gadget                 1       19.99
Thingamajig           10        7.50
------------------------------------
Total                          34.99
Thank you for the large order!

This works well for text that developers own, like CLI output, logs and generated code. For long outputs with lots of logic, a StringBuffer is easier to read than one big string; see Building from parts and Concatenation and interpolation.

Interpolation has two limits:

Simple placeholder substitution

When users or admins edit a template, for example a notification message stored in a database, you need placeholders that are filled at run time. For plain text, a regular expression and replaceAllMapped are enough:

final _placeholder = RegExp(r'\{\{\s*([\w.]+)\s*\}\}');

/// Replaces {{name}} with values[name]. Throws on unknown names
/// unless [missing] is given.
String fill(String template, Map<String, Object?> values, {String Function(String name)? missing}) {
  return template.replaceAllMapped(_placeholder, (m) {
    final name = m[1]!;
    if (values.containsKey(name)) return '${values[name] ?? ''}';
    if (missing != null) return missing(name);
    throw ArgumentError('No value for placeholder "$name"');
  });
}

void main() {
  // A template stored in a config file or a database, edited by users.
  const tpl = 'Hi {{ name }}, your order #{{order}} ships on {{date}}.';
  print(fill(tpl, {'name': 'Alice', 'order': 1042, 'date': '2026-10-20'}));

  print(fill(tpl, {'name': 'Bob'}, missing: (n) => '{{$n}}'));

  try {
    fill(tpl, {'name': 'Carol'});
  } on ArgumentError catch (e) {
    print('Error: ${e.message}');
  }

  // Values are inserted once; placeholders inside values are not expanded.
  print(fill('{{a}} and {{b}}', {'a': '{{b}}', 'b': 'B'}));
}

Output:

Hi Alice, your order #1042 ships on 2026-10-20.
Hi Bob, your order #{{order}} ships on {{date}}.
Error: No value for placeholder "order"
{{b}} and B

A single replaceAllMapped pass matters. If you call replaceAll once per key instead, a value that contains {{b}} gets expanded by a later replacement, so users can pull in data you didn't mean to show them. Regular expressions are covered in Regular Expressions.

Once you need loops, conditionals or HTML escaping, stop extending this and use a real engine.

Escaping HTML

Any text that goes into HTML must be escaped, or a user who types <script> can run code in other users' browsers. HtmlEscape from dart:convert does it, with modes for text and for attribute values. The XSS section of Application security explains the modes and the cases that escaping doesn't cover, like javascript: URLs.

Calling HtmlEscape by hand everywhere is easy to forget. A safer design is to make "safe HTML" a type: escaped text and trusted markup become Html values, and a builder escapes everything that isn't already Html:

import 'dart:convert';

/// A string that is known to be safe HTML.
final class Html {
  final String markup;
  const Html._(this.markup);

  /// Escapes plain text so it can go anywhere in an HTML document.
  factory Html.text(Object? value) =>
      Html._(const HtmlEscape().convert('${value ?? ''}'));

  /// Trusted markup, for example from your own code. Never use with user input.
  const Html.raw(String markup) : this._(markup);

  @override
  String toString() => markup;
}

/// Builds an element. Children that are not Html are escaped as text.
Html el(String tag, [List<Object?> children = const [], Map<String, Object?> attrs = const {}]) {
  final a = StringBuffer();
  attrs.forEach((name, value) {
    if (value == null || value == false) return;
    if (value == true) {
      a.write(' $name');
    } else {
      a.write(' $name="${const HtmlEscape(HtmlEscapeMode.attribute).convert('$value')}"');
    }
  });
  final body = children.map((c) => c is Html ? c.markup : Html.text(c).markup).join();
  return Html.raw('<$tag$a>$body</$tag>');
}

class User {
  final String name;
  final String email;
  final bool admin;
  User(this.name, this.email, {this.admin = false});
}

Html userRow(User u) => el('tr', [
      el('td', [u.name]),
      el('td', [el('a', [u.email], {'href': 'mailto:${u.email}'})]),
      el('td', [u.admin ? Html.raw('<b>admin</b>') : 'user']),
    ]);

Html userTable(List<User> users) => el('table', [
      el('tr', [el('th', ['Name']), el('th', ['Email']), el('th', ['Role'])]),
      ...users.map(userRow),
    ], {'class': 'users', 'hidden': users.isEmpty});

void main() {
  final users = [
    User('Alice', 'alice@example.com', admin: true),
    User('<script>alert(1)</script>', 'x"onmouseover="alert(2)@evil.example'),
  ];
  print(userTable(users).markup.replaceAll('<tr>', '\n<tr>'));
  print(userTable([]).markup);
}

Output:

<table class="users">
<tr><th>Name</th><th>Email</th><th>Role</th></tr>
<tr><td>Alice</td><td><a href="mailto:alice@example.com">alice@example.com</a></td><td><b>admin</b></td></tr>
<tr><td>&lt;script&gt;alert(1)&lt;&#47;script&gt;</td><td><a href="mailto:x&quot;onmouseover=&quot;alert(2)@evil.example">x&quot;onmouseover=&quot;alert(2)@evil.example</a></td><td>user</td></tr></table>
<table class="users" hidden><tr><th>Name</th><th>Email</th><th>Role</th></tr></table>

The script tag and the attempt to break out of the href attribute both come out as harmless text. Components are plain Dart functions (userRow, userTable), so they compose, take typed arguments, and the compiler catches typos.

Html must be a class, not an extension type. Extension types are erased at run time, so an extension type Html(String _) makes c is Html true for every String, and nothing gets escaped. It's an easy mistake, and the output looks fine until someone enters a <script> tag.

Mustache templates

Mustache is a "logic-less" template language: the template has tags for values, sections and partials, but no expressions or function calls. All logic stays in Dart. Implementations exist for most languages, so the same templates can be used by a Dart server and a JavaScript front end.

Add the package:

dart pub add mustache_template

A Template is parsed when you construct it and can then be rendered any number of times:

import 'package:mustache_template/mustache_template.dart';

const source = '''
<h1>{{title}}</h1>
<p>Posted by {{author.name}} &lt;{{author.email}}&gt;</p>
{{#hasTags}}
<ul class="tags">
  {{#tags}}
  <li>{{.}}</li>
  {{/tags}}
</ul>
{{/hasTags}}
{{^tags}}
<p>No tags.</p>
{{/tags}}
{{! Comments are not rendered. }}
<div class="body">{{{bodyHtml}}}</div>
<p>Escaped: {{bodyHtml}}</p>
''';

void main() {
  // Parse once, render many times.
  final template = Template(source, name: 'post.html');

  print(template.renderString({
    'title': 'Templates & You',
    'author': {'name': 'Alice', 'email': 'alice@example.com'},
    'tags': ['dart', 'web'],
    'hasTags': true,
    'bodyHtml': '<em>Hello</em>',
  }));

  print(template.renderString({
    'title': '<script>alert(1)</script>',
    'author': {'name': 'Bob', 'email': 'bob@example.com'},
    'tags': <String>[],
    'hasTags': false,
    'bodyHtml': '',
  }));
}

Output:

<h1>Templates &amp; You</h1>
<p>Posted by Alice &lt;alice@example.com&gt;</p>
<ul class="tags">
  <li>dart</li>
  <li>web</li>
</ul>
<div class="body"><em>Hello</em></div>
<p>Escaped: &lt;em&gt;Hello&lt;&#x2F;em&gt;</p>

<h1>&lt;script&gt;alert(1)&lt;&#x2F;script&gt;</h1>
<p>Posted by Bob &lt;bob@example.com&gt;</p>
<p>No tags.</p>
<div class="body"></div>
<p>Escaped: </p>

The tags:

Tag Meaning
{{name}} value, HTML-escaped
{{a.b.c}} nested value: values['a']['b']['c']
{{{name}}} or {{& name}} value, not escaped. Only for trusted HTML
{{#name}}...{{/name}} section: repeated for each list element, rendered once for true or a map, skipped for false, null or an empty list
{{^name}}...{{/name}} inverted section: rendered only if the value is false, null or an empty list
{{.}} the current element inside a section over a list
{{! comment }} comment, produces no output
{{> name}} partial: include another template

A tag that sits alone on a line (a "standalone" tag like {{#tags}} above) doesn't leave an empty line in the output, so you can indent templates naturally. Escaping turns / into &#x2F;, which browsers decode back to /, so it does no harm in text or attributes.

Maps, not objects

mustache_template only looks up names in Maps (and List indexes like {{items.0}}). It doesn't use reflection, so it can't read fields or getters of your classes; {{tags.isNotEmpty}} fails too, which is why the example above passes a separate hasTags. Convert objects to a "view" map that holds exactly what the template needs, including computed and formatted values:

import 'package:mustache_template/mustache_template.dart';

class Product {
  final String name;
  final int cents;
  final int stock;
  Product(this.name, this.cents, this.stock);

  // mustache_template only looks inside Maps and Lists,
  // so expose what the template needs, including computed values.
  Map<String, Object?> toView() => {
        'name': name,
        'price': '\$${(cents / 100).toStringAsFixed(2)}',
        'inStock': stock > 0,
        'lowStock': stock > 0 && stock < 5,
      };
}

void main() {
  final products = [Product('Pen', 199, 120), Product('Lamp', 2450, 3), Product('Desk', 18900, 0)];

  final t = Template('''
{{#products}}
- {{name}} {{price}}{{#lowStock}} (only a few left){{/lowStock}}{{^inStock}} (sold out){{/inStock}}
{{/products}}
''', name: 'products');
  print(t.renderString({'products': [for (final p in products) p.toView()]}));

  // Passing the object itself fails in strict mode.
  try {
    Template('{{name}}', name: 'raw').renderString(products.first);
  } on TemplateException catch (e) {
    print('${e.message} (${e.templateName} line ${e.line}, column ${e.column})');
  }

  // Typos are caught at render time...
  try {
    Template('Hello {{nmae}}!', name: 'greeting').renderString({'name': 'Ann'});
  } on TemplateException catch (e) {
    print(e);
  }

  // ...and syntax errors when the template is parsed.
  try {
    Template('{{#items}}<li>{{.}}</li>', name: 'list');
  } on TemplateException catch (e) {
    print(e.message);
  }

  // Lenient mode renders missing values as empty strings.
  print(Template('Hello {{nmae}}!', lenient: true).renderString({'name': 'Ann'}));
}

Output:

- Pen $1.99
- Lamp $24.50 (only a few left)
- Desk $189.00 (sold out)

Value was missing for variable tag: name. (raw line 1, column 1)
Value was missing for variable tag: nmae. (greeting:1:7)
Hello {{nmae}}!
      ^

Unclosed tag: 'items'.
Hello !

The default strict mode throws a TemplateException for unknown names, with the template name, line and column. That's what you want during development: a typo fails loudly instead of rendering an empty string. Always pass name: (usually the file name) so the error says which template failed. lenient: true silently renders missing values as nothing; use it only for templates written by users, where a missing value shouldn't break the page.

Keeping logic out of templates has a benefit beyond Mustache's rules: a view map is easy to unit test, and the template can't trigger database queries or other side effects.

What counts as true in a section

Sections are meant for booleans, lists and maps. Strings and numbers behave in a way that surprises people coming from JavaScript:

import 'package:mustache_template/mustache_template.dart';

final show = Template('{{#v}}shown{{/v}}', name: 'show');
final hide = Template('{{^v}}shown{{/v}}', name: 'hide');

String run(Template t, Object? v) {
  try {
    final s = t.renderString({'v': v});
    return s.isEmpty ? '-' : s;
  } on TemplateException {
    return 'error';
  }
}

void main() {
  print('value   {{#v}}       {{^v}}');
  for (final v in [true, false, null, <int>[], [1, 2], '', 'text', 0]) {
    final label = v is String ? "'$v'" : '$v';
    print('${label.padRight(8)}${run(show, v).padRight(12)}${run(hide, v)}');
  }
}

Output:

value   {{#v}}       {{^v}}
true    shown       -
false   -           shown
null    -           shown
[]      -           shown
[1, 2]  shownshown  -
''      shown       error
'text'  shown       error
0       shown       error

An empty string or 0 doesn't hide a section, and an inverted section over a string throws. Pass an explicit bool, like 'hasResults': results.isNotEmpty.

Partials, layouts and loading from files

Real sites keep templates in files and share a layout (<head>, navigation, footer) across pages. Mustache has no inheritance, but partials and a partialResolver function get you there. Given these files:

templates/layout.mustache:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>{{title}} - My Site</title>
</head>
<body>
  {{> header}}
  <main>
{{> content}}
  </main>
</body>
</html>

templates/header.mustache:

<nav>{{#nav}}<a href="{{url}}"{{#active}} class="active"{{/active}}>{{label}}</a> {{/nav}}</nav>

templates/users.mustache:

<h1>{{title}}</h1>
<ul>
  {{#users}}
{{> user_item}}
  {{/users}}
</ul>

templates/user_item.mustache:

  <li>{{name}} ({{role}})</li>

A small class loads templates on first use, caches the parsed Template, and resolves {{> content}} in the layout to the page being rendered:

import 'dart:io';
import 'package:mustache_template/mustache_template.dart';

/// Loads templates from a directory, parses each one once and caches it.
class Templates {
  final String dir;
  final _cache = <String, Template>{};
  final _pages = <String, Template>{};
  Templates(this.dir);

  Template get(String name) => _cache.putIfAbsent(name, () {
        final file = File('$dir/$name.mustache');
        return Template(file.readAsStringSync(), name: file.path, partialResolver: get);
      });

  /// Renders [page] inside the layout: {{> content}} in the layout
  /// resolves to the page template.
  String renderPage(String page, Map<String, Object?> values) {
    final t = _pages.putIfAbsent(
      page,
      () => Template(
        get('layout').source,
        name: 'layout($page)',
        partialResolver: (name) => name == 'content' ? get(page) : get(name),
      ),
    );
    return t.renderString(values);
  }
}

void main() {
  final templates = Templates('templates');
  final html = templates.renderPage('users', {
    'title': 'Users',
    'nav': [
      {'url': '/', 'label': 'Home', 'active': false},
      {'url': '/users', 'label': 'Users', 'active': true},
    ],
    'users': [
      {'name': 'Alice', 'role': 'admin'},
      {'name': 'Bob & Co', 'role': 'editor'},
    ],
  });
  print(html);
}

Output:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Users - My Site</title>
</head>
<body>
  <nav><a href="&#x2F;">Home</a> <a href="&#x2F;users" class="active">Users</a> </nav>
  <main>
<h1>Users</h1>
<ul>
  <li>Alice (admin)</li>
  <li>Bob &amp; Co (editor)</li>
</ul>
  </main>
</body>
</html>

Notes:

Text output, lambdas and delimiters

For anything that isn't HTML, such as plain-text emails, Markdown or config files, turn escaping off with htmlEscapeValues: false. Otherwise O'Brien & Sons comes out as O&#x27;Brien &amp; Sons:

import 'dart:io';
import 'package:mustache_template/mustache_template.dart';

void main() {
  // Text output (email, config file): turn off HTML escaping.
  final email = Template('''
Hello {{name}},

Your order "{{product}}" for {{total}} has shipped.
{{#items}}
  * {{qty}} x {{title}}
{{/items}}

{{#bold}}Thanks for shopping with us{{/bold}}
<{{url}}>
''', name: 'email.txt', htmlEscapeValues: false);

  final values = {
    'name': "O'Brien & Sons",
    'product': 'Desk <oak>',
    'total': '\$189.00',
    'items': [
      {'qty': 1, 'title': 'Desk <oak>'},
      {'qty': 4, 'title': 'Chair'},
    ],
    // Lambdas transform the rendered text of a section.
    'bold': (LambdaContext ctx) => '*${ctx.renderString().toUpperCase()}*',
    'url': 'https://shop.example/orders/42?ref=mail&lang=en',
  };

  // render() writes to any StringSink: a StringBuffer, stdout, a file, an HTTP response.
  email.render(values, stdout);

  // Change delimiters when the output itself uses {{ }}, e.g. a Vue or Angular template.
  final vue = Template('<p>[[greeting]], {{ user.name }}</p>', delimiters: '[[ ]]');
  print(vue.renderString({'greeting': 'Hi'}));

  // Or switch them inside the template.
  print(Template('{{=<% %>=}}<% x %> stays {{literal}}').renderString({'x': 1}));
}

Output:

Hello O'Brien & Sons,

Your order "Desk <oak>" for $189.00 has shipped.
  * 1 x Desk <oak>
  * 4 x Chair

*THANKS FOR SHOPPING WITH US*
<https://shop.example/orders/42?ref=mail&lang=en>
<p>Hi, {{ user.name }}</p>
1 stays {{literal}}

A lambda is a function in the values map used as a section. It receives a LambdaContext; ctx.renderString() renders the section's content, and whatever the function returns is written to the output without escaping. Lambdas are the place for formatting helpers (dates, currencies, translations) that would otherwise have to be pre-computed in every view map.

render(values, sink) writes straight into a StringSink, which avoids building one big string when writing to a file or an IOSink.

Parsing cost

Parsing is the expensive part, so create each Template once (at startup, or cached as above), not per request. A rough measurement, compiled with dart compile exe:

import 'package:mustache_template/mustache_template.dart';

const source = '<ul>{{#items}}<li>{{name}}: {{price}}</li>{{/items}}</ul>';
final data = {
  'items': [for (var i = 0; i < 20; i++) {'name': 'Item $i', 'price': i * 1.5}],
};

void main() {
  const n = 20000;
  final sw = Stopwatch()..start();
  for (var i = 0; i < n; i++) {
    Template(source).renderString(data);
  }
  print('parse + render: ${(sw.elapsedMicroseconds / n).toStringAsFixed(1)} us');

  final t = Template(source);
  sw.reset();
  for (var i = 0; i < n; i++) {
    t.renderString(data);
  }
  print('render only:    ${(sw.elapsedMicroseconds / n).toStringAsFixed(1)} us');
}

Output:

parse + render: 24.1 us
render only:    15.2 us

Even this tiny template spends a third of its time parsing. For more reliable numbers see Benchmarks.

Jinja templates

If you want more than Mustache offers, such as template inheritance with {% extends %} and {% block %}, expressions, loop.index and filters, the jinja package implements most of Python's Jinja2 syntax:

dart pub add jinja
import 'package:jinja/jinja.dart';

void main() {
  final env = Environment(
    loader: MapLoader({
      'base.html': '''
<html>
<head><title>{% block title %}{% endblock %} - Shop</title></head>
<body>
{% block content %}{% endblock %}
</body>
</html>''',
      'orders.html': '''
{% extends "base.html" %}
{% block title %}Orders{% endblock %}
{% block content %}
<h1>{{ user.name | escape }}'s orders ({{ orders | length }})</h1>
<table>
{% for o in orders %}
  <tr class="{{ loop.cycle('odd', 'even') }}">
    <td>{{ loop.index }}</td>
    <td>{{ o.item | escape }}</td>
    <td>{{ o.price | money }}</td>
    <td>{{ o.status | default('pending') | upper }}</td>
  </tr>
{% else %}
  <tr><td colspan="4">No orders</td></tr>
{% endfor %}
</table>
<p>Total: {{ total | money }}</p>
<p>Unescaped: {{ user.name }}</p>
{% endblock %}''',
    }),
    filters: {'money': (num v) => '\$${v.toStringAsFixed(2)}'},
    trimBlocks: true,
    leftStripBlocks: true,
  );

  final template = env.getTemplate('orders.html');
  final orders = [
    {'item': 'Pen & ink', 'price': 3.5, 'status': 'shipped'},
    {'item': 'Lamp', 'price': 24.0, 'status': null},
  ];
  print(template.render({
    'user': {'name': '<b>Ann</b>'},
    'orders': orders,
    'total': orders.fold<num>(0, (s, o) => s + (o['price'] as num)),
  }));
}

Output:

<html>
<head><title>Orders - Shop</title></head>
<body>
<h1>&lt;b&gt;Ann&lt;/b&gt;'s orders (2)</h1>
<table>
  <tr class="odd">
    <td>1</td>
    <td>Pen &amp; ink</td>
    <td>$3.50</td>
    <td>SHIPPED</td>
  </tr>
  <tr class="even">
    <td>2</td>
    <td>Lamp</td>
    <td>$24.00</td>
    <td>PENDING</td>
  </tr>
</table>
<p>Total: $27.50</p>
<p>Unescaped: <b>Ann</b></p>
</body>
</html>

Things to know about the Dart port:

Serving HTML from a web server

In a server, parse templates at startup, render per request, and set Content-Type with a charset. Here's a Shelf handler (see Hello World and HTTP middleware for more on Shelf), tested with an XSS attempt in the query string:

import 'dart:convert';
import 'dart:io';

import 'package:mustache_template/mustache_template.dart';
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart' as io;

// Parsed once at startup; a parse error stops the server before it accepts requests.
final _page = Template('''
<!DOCTYPE html>
<html lang="en">
<head><meta charset="utf-8"><title>Search</title></head>
<body>
<form><input name="q" value="{{q}}"></form>
{{#searched}}<p>Results for <b>{{q}}</b>: {{count}}</p>{{/searched}}
</body>
</html>
''', name: 'search.html');

Response search(Request request) {
  final q = request.url.queryParameters['q'] ?? '';
  final html = _page.renderString({'q': q, 'searched': q.isNotEmpty, 'count': q.length});
  return Response.ok(html, headers: {'content-type': 'text/html; charset=utf-8'});
}

Future<void> main() async {
  final server = await io.serve(search, InternetAddress.loopbackIPv4, 0);
  print('Listening on port ${server.port}');

  final client = HttpClient();
  final uri = Uri.http('127.0.0.1:${server.port}', '/', {'q': '"><script>alert(1)</script>'});
  final res = await (await client.getUrl(uri)).close();
  print('${res.statusCode} ${res.headers.contentType}');
  print(await res.transform(utf8.decoder).join());

  client.close();
  await server.close();
}

Output:

Listening on port 53813
200 text/html; charset=utf-8
<!DOCTYPE html>
<html lang="en">
<head><meta charset="utf-8"><title>Search</title></head>
<body>
<form><input name="q" value="&quot;&gt;&lt;script&gt;alert(1)&lt;&#x2F;script&gt;"></form>
<p>Results for <b>&quot;&gt;&lt;script&gt;alert(1)&lt;&#x2F;script&gt;</b>: 27</p>
</body>
</html>

The " that would close the value attribute is escaped, so the injected tag stays inside the attribute as text. Always set the content type: for a String body without one, Shelf sends application/octet-stream; charset=utf-8, and browsers download the page instead of displaying it.

Choosing an approach

Need Use
Text owned by developers: CLI output, generated code functions with string interpolation or StringBuffer
User-editable messages with a few {{fields}} one replaceAllMapped pass
HTML built in Dart with compile-time checks an Html class and builder functions that escape by default
HTML templates in files, shared with designers or other languages mustache_template (escapes by default)
Inheritance, expressions and filters jinja, escaping every value with `
Plain-text emails and config files from templates mustache_template with htmlEscapeValues: false

Summary

Task How
Escape text for HTML const HtmlEscape().convert(s), HtmlEscapeMode.attribute for attributes
Parse a Mustache template Template(source, name: 'file.html'), once
Render t.renderString(values) or t.render(values, sink)
Value, escaped / raw {{name}} / {{{name}}} or {{& name}}
Loop or condition {{#list}}...{{/list}}, {{#flag}}...{{/flag}}, {{^list}}empty{{/list}}
Pass objects convert to Map (a view model); no getters or methods in templates
Missing values strict by default (TemplateException), lenient: true to ignore
Include templates / layouts {{> name}} with partialResolver: (name) => ...
Helpers lambdas: (LambdaContext ctx) => ...
Non-HTML output htmlEscapeValues: false
Output uses {{ }} delimiters: '[[ ]]' or {{=<% %>=}}
Jinja inheritance Environment(loader: ...), {% extends %}, {% block %}
Jinja escaping manual: `{{ value
Serve HTML Response.ok(html, headers: {'content-type': 'text/html; charset=utf-8'})

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents