glemplate

Package Version Hex Docs

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, &lt;Nicd&gt;!</b>"

The main modules:

Using templates with Glemplate has two main things to deal with:

  1. parsing templates into AST with the parser, and
  2. 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

Installation

This package can be added to your Gleam project:

gleam add glemplate

and its documentation can be found at https://hexdocs.pm/glemplate.

Search Document