@frctl/nunjucks-helpers
v0.3.0
Published
A collection of Nunjucks helpers for Fractal.
Downloads
296
Keywords
Readme
Fractal Nunjucks Helpers
A collection of Nunjucks helpers for Fractal projects.
Requires use of the Nunjucks adapter (or similar) to enable Nunjucks templates in Fractal.
Installation and Usage
Loading all helpers
If you wish to load all helpers into the template engine instance, you can auto-load them via the adapter:
// fractal.js
const fractal = require('@frctl/fractal');
fractal.engine('nunjucks', '@frctl/nunjucks-adapter', {
loadHelpers: true
});
Loading individual helpers
If you want to load individual helpers, you will first need to install this library:
npm i @frctl/nunjucks-helpers --save
You can then initialise the helpers and pick the the ones you want to use
// fractal.js
const fractal = require('@frctl/fractal');
const helpers = require('@frctl/nunjucks-helpers'); // require the helpers
helpers.use(fractal); // initialise the helpers with the fractal instance
fractal.engine('nunjucks', '@frctl/nunjucks-adapter', {
extensions: {
'render': helpers.require('extensions/render') // use the 'render' extension
}
});
Extensions
render
The render
extension renders a component (referenced by it's handle) using the context data provided to it in the template. If no data is provided, it will use the context data defined within it's configuration file, if present.
This can be very useful as an alternative to using an include
to import sub-components. Include
'd components do not pull in their own context so using render
instead can help prevent repetition of context data in the configuration files of components that include sub-components.
<!-- pass in data for rendering -->
{% render '@example', {title: 'An Example'} %}
{% render '@example', someData %}
<!-- use the config file data for rendering -->
{% render '@example' %}
You can also pass in a partial data object (i.e. containing only some of the properties the component expects) and then pass a third argument of true
to the tag to populate the missing items from the default context data. This allows you to override only the items you need to for this instance of the rendered component.
<!-- will get any missing properties from the component context data -->
{% render '@another-example', {title: 'Another Example'}, true %}
context
Outputs the resolved context data for a component.
{% context '@example' %}
<!-- Outputs:
{
"foo": "bar",
"baz": "bar"
}
-->
view
Outputs the raw view template contents for the specified component.
{% view '@example' %}
<!-- Outputs:
<p>{{ text }}</p>
-->