1
Caching
harttle edited this page 2019-10-14 14:11:40 +08:00

In a typical website project, we'll have a directory of view templates and they'll be rendered multiple times. In production environment the template files are not likely to be changed overtime (other than re-deployments). Thus it's a waste of time to repeatedly read from file system and parse the template string each time. LiquidJS provides multiple ways to cache the parsed templates to improve performance.

Programmaticly

The parse, parseFile, parseFileSync APIs are used to parse templates from string or files. The result template can be then rendered multiple times with different context.

Parse from string:

var tpl = engine.parse('{{name | capitalize}}');

engine.renderSync(tpl, {name: 'alice'}) // 'Alice'
engine.renderSync(tpl, {name: 'bob'}) // 'Bob'

Parse from file:

var tpl = engine.parseFileSync('hello');    // contents of `hello.liquid`: {{name}}

engine.renderSync(tpl, {name: 'alice'}) // 'Alice'
engine.renderSync(tpl, {name: 'bob'}) // 'Bob'

The cache Option

The [cache option][cache] can be set to instruct liquidjs to use cached parsed templates each time you call renderFile or renderFileSync.

var { Liquid } = require('liquidjs');
var engine = new Liquid({
    cache: true
});

// liquidjs parses the hello.liquid, then renders it with {name: 'alice'}
engine.renderFileSync('hello', {name: 'alice'})

// liquidjs finds the cached template, then renders it with {name: 'bob'}
engine.renderFileSync('hello', {name: 'bob'})