This module allows Mustache.js templates to be used with DADI Web.
-
Add this module as a dependency:
npm install dadi-web-mustachejs --save
-
Include it in the
engines
array passed to Web:require('@dadi/web')({ engines: [ require('dadi-web-mustachejs') ] })
The following configuration parameters can be added to the global Web config file, under engines.mustache
.
Paths required by Mustache.
- Format:
Object
- Default:
{ { helpers: 'workspace/utils/helpers' } }
Partials must be registered with Mustache before they can be used in a template. This library takes care of the registration for you, simply supply the path to your partials in the configuration option additionalTemplates
.
pages/
|_ partials/
|_ |_ common/
|_ |_ |_ header.mustache
|_ contact-info.mustache
|_ home.mustache
Partials are referenced by their relative path, minus the file extension. After loading the above hierarchy of templates and partials, to include header.mustache
from the page contact-info.mustache
, you would use the following syntax:
{{> 'partials/common/header' }}
To use helpers supply the path to your helpers in the main Web configuration file:
"engines": {
"mustache": {
"paths": {
"helpers": "workspace/helpers"
}
}
}
Helpers can be individual JavaScript files within the specifed directory, or all in a single file.
Example:
/*
* Returns the full name and price of the supplied product
* The function receives the current context
* Usage: {{ renderProduct }}
*/
module.exports = function () {
return `helper: ${this.name} - £${this.price}`
}
This function is now available in your templates, to be used as follows. The function receives the current context, in the following example it receives a product
object with properties name
and price
.
{{#products}}
<li>{{renderProduct}}</li>
{{/products}}
Read more in the Mustache documentation at https://github.com/janl/mustache.js
Open a pull request or raise an issue.