glemplate/README.md

62 lines
2.3 KiB
Markdown
Raw Normal View History

2023-02-26 20:48:34 +00:00
# glemplate
[![Package Version](https://img.shields.io/hexpm/v/glemplate)](https://hex.pm/packages/glemplate)
[![Hex Docs](https://img.shields.io/badge/hex-docs-ffaff3)](https://hexdocs.pm/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
```gleam
import gleam/map
import glemplate/parser
import glemplate/html
import glemplate/assigns
let template = "<b>Welcome, <%= name %>!</b>"
assert Ok(tpl) = parser.parse_to_template(template, "input.html.glemp")
let assigns = assigns.from_list([#("name", assigns.String("<Nicd>"))])
let template_cache = map.new()
html.render(tpl, assigns, template_cache) // "<b>Welcome, &lt;Nicd&gt;!</b>"
```
The main modules:
- [glemplate/parser](glemplate/parser.html): The parser implements and documents the string
template syntax.
- [glemplate/ast](glemplate/ast.html): The abstract syntax tree (AST) is the data format of the
parsed templates.
- [glemplate/renderer](glemplate/renderer.html): 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](glemplate/html.html) and [glemplate/text](glemplate/text.html) have helper
functions for rendering HTML and plain text templates.
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…
## 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:
```sh
gleam add glemplate
```
and its documentation can be found at <https://hexdocs.pm/glemplate>.