Skip to main content

Loading Templates

You can load templates from a file system or database, for example, by creating an Environment and configuring a template loader. You'd also need a loader if you want to use the built-in include or render tags.

Environment.getTemplate() and Environment.getTemplateSync() accept a template name and return a Template that is bound to the environment, ready to be rendered. The configured loader is responsible for interpreting template names. In the case of a NodeFileSystemLoader, the name would be a file name, relative to the loader's search path.

This example assumes a folder called templates exists in the current working directory, and that template files index.html and some-list.html exist within it.

templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>{{ page_title }}</title>
</head>
<body>
<h1>{{ heading }}</h1>
{% render 'some-list.html' with people %}
</body>
</html>
templates/some-list.html
<ul>
{% for person in people %}
<li>{{ person.name }}</li>
{% endfor %}
</ul>

By default, every Environment is created with an empty MapLoader. Specify an alternative template loader using the loader option.

import { Environment, NodeFileSystemLoader } from "liquidscript";

const env = new Environment({
loader: new NodeFileSystemLoader("./templates/", {
fileExtension: ".liquid",
}),
});

const template = env.getTemplateSync("index.html");
const result = template.renderSync({
heading: "Some List",
page_title: "Awesome Title",
people: [{ name: "John" }, { name: "Sally" }],
});

console.log(result);
Output
<!DOCTYPE html>
<html lang="en">
<head>
<title>Awesome Title</title>
</head>
<body>
<h1>Some List</h1>
<ul>
<li>John</li>
<li>Sally</li>
</ul>
</body>
</html>

Built-In Template Loaders

LiquidScript includes some generic templates loaders, and some that are specific to Node.js or the web browser.

Generic

LoaderDescription
MapLoaderA template loader that uses a Map of string names to template source code strings.
ObjectLoaderA template loader that uses a plain object to map string names to template source code string.
ChoiceLoaderA template loader that will try each of an array of loaders until a matching template is found.

Node.js

LoaderDescription
NodeFileSystemLoaderA template loader that reads templates from a file system using Node's fs module.
CachingNodeFileSystemLoaderA template loader that caches templates read from a file system.

Browser

LoaderDescription
FetchLoaderA template loader that fetches templates using the Fetch API.
XMLHttpRequestLoaderA template loader that uses XMLHttpRequest to fetch templates.