glemplate
Glemplate is a simplistic template engine for Gleam. The aim was to learn how to make such a thing and fill simple use cases. At this stage, it can be used for simple plain text and HTML templates, and for other contexts by supplying a custom encoding function.
Quick start
import gleam/dict
import glemplate/parser
import glemplate/html
import glemplate/assigns
let template = "<b>Welcome, <%= name %>!</b>"
let p = parser.new()
let assert Ok(tpl) = parser.parse_to_template(template, "input.html.glemp", p)
let assigns = assigns.from_list([#("name", assigns.String("<Nicd>"))])
let template_cache = dict.new()
html.render(tpl, assigns, template_cache) // "<b>Welcome, <Nicd>!</b>"
The main modules:
- glemplate/parser: The parser implements and documents the string template syntax.
- glemplate/ast: The abstract syntax tree (AST) is the data format of the parsed templates.
- glemplate/renderer: The renderer takes in the parsed AST, input data, and a cache of templates, and renders the template into an output string builder.
- glemplate/html and glemplate/text have helper functions for rendering HTML and plain text templates.
Using templates with Glemplate has two main things to deal with:
- parsing templates into AST with the parser, and
- rendering that AST into some output with assigns (input data).
Since Gleam has no metaprogramming, the parsing of templates needs to be done at startup time (or whenever deemed necessary when templates have changed). The resulting AST should be stored for later use in e.g. ETS, process state, persistent_term…
Glemplate does not offer any tooling for reading templates currently. You will need to use whatever method appropriate for your situation: reading from files, compiling the strings in the app, reading from a database…
When stored in files, it’s suggested that templates use the file naming style
name.<type>.glemp
, where <type>
signifies the type of content rendered from the template. E.g.
user.html.glemp
.
Limitations
- Static values in templates in place of variables aren’t supported.
- It’s possible to create infinite loops with child templates, it’s not recommended to give access to writing templates to untrusted users.
- Calling functions from templates is not supported.
Installation
This package can be added to your Gleam project:
gleam add glemplate
and its documentation can be found at https://hexdocs.pm/glemplate.