Available since v0.7.0
local template = require "template"
Template provides a simple interface to the Jinja2 templating engine.
-- The template package itself provides a single top-level function `renderstring(str, ctx)`
local rendered = template.renderstring("Hello, {{ name }}!", { name = "World" })
assert(rendered == "Hello, World!")
Using a Library for engine customization
local template = require("template").library {
-- Load templates from a filesystem directory
directory = "path/to/templates",
-- Or define templates inline
templates = {
base = [[
This is the base template
{% block user %}{% endblock %}
]],
user = [[
{% extends "base" %}
{% block user %}
Hello, {{ user.name }}!
{% endblock %}
]]
},
-- Set the template autoescaping behavior.
-- Can be one of "html", "json", or "none". Defaults to "html"
autoescape = "html",
keep_trailing_newline = true,
trim_blocks = true,
lstrip_blocks = true
}
local rendered = template:render("user", { user = { name = "Friend" } })
assert(rendered == [[
This is the base template
Hello, Friend!
]])
-- Can also render an inline template with the library
local rendered = template:renderstring([[
{% extends "base" %}
{% block user %}
Good Job, {{ user.name }}!
{% endblock %}
]], { user = { name = "Friend" } })
assert(rendered == [[
This is the base template
Good Job, Friend!
]])
-- Add and remove templates to/from the library dynamically
template:add("user", [[
{% extends "base" %}
{% block user %}
Good Job, {{ user.name }}!
{% endblock %}
]])
template:remove("user")
-- Remove all templates from the library
template:clear()