Helpers & filters
Helpers are functions accessible from pages and layouts that help to render the content.
Filters
There are different types of helpers; the most common type is a filter, used to transform values. Some template engines, like Nunjucks, have several builtin filters, but you can add more:
// Filter to convert a string to uppercase
site.filter("uppercase", (value) => value.toUpperCase());
Now, use it in your templates:
<h1>{{ title | uppercase }}</h1>
export default function (data, filters) {
const text = filters.uppercase(data.title);
return `<h1>${text}</h1>`;
}
<h1><%= filters.uppercase(title) %></h1>
If your filter is asynchronous, set true
as the third argument:
site.filter("async_filter", async (value) => value, true);
Not all template engines support async filters. {.tip}
Builtin filters
Lume includes the following convenient pre-installed filters:
- md: Allows to render Markdown content to HTML. More info
- njk: Allows to render Nunjucks content to HTML. More info
- url / htmlUrl: Allows to normalize URLs. More info
Helpers
Some template engines allow adding other helpers different from filters, like custom tags. To configure that, there's the helper()
method that allows adding any generic helper.
site.helper("uppercase", (text) => text.toUpperCase(), { type: "tag" });
{{ uppercase user.name }}
The third argument is an object with different properties:
type
: The type of helper. It can betag
,filter
or any other, depending on the template engine.async
: Settrue
to configure the helper as async.body
: Settrue
to configure that the helper accept a body (supported only by nunjucks custom tags)
Example of custom tag with body:
site.helper("uppercase", (body) => body.toUpperCase(), {
type: "tag",
body: "true",
});
{{ uppercase }}
Hello, {{ user.name }}
{{ enduppercase }}
Note: The method filter()
is just a shortcut of helper()
with { type: "filter" }
. {.tip}