README.md

# 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/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:

- [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…

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:

```sh
gleam add glemplate
```

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