Helper that automatically loads nunjucks modules (view, schema and example.js for using the template.
npm install @firstandthird/module-loader
or
yarn add @firstandthird/module-loader
const moduleLoader = require('@firstandthird/module-loader');
const modules = await moduleLoader({
path: `/modules`
});
const theModule = modules['my_module'];
const output = theModule.render({ val1: 'hello', val2: 'world' });
Each module in the returned set of modules will contain the following methods and properties:
-
renderRaw()
A function that takes in the context to apply to the view, attempts to validate the context and then returns the rendered string, eg:
theModule.renderRaw({ val1: 'hello', val2: 'world' });
renderRaw() will log an error message if the validation check fails, but it has no error handling. If there is an error rendering the view then it will throw the error and you will need to handle it yourself in code.
-
render()
is a wrapper for the renderRaw method that will attempt to safely render and handle any errors for you:
theModule.render({ val1: 'hello', val2: 'world' });
-
getExamples()
This will render and return an example of the template, along with the example data used to render it and any config data supplied to the module.
-
fullPath
The full path to the module
-
name
The name of the module
-
exampleData
This will return an array containing the config and any example data used by the getExamples() function.
A module is a sub-directory consisting of 3 parts:
-
view.njk
A nunjucks .njk file containing the template to be rendered:
<div> This is an example <h1>{{ val1 }}</h1> <p>{{ val2 }}</p> </div>
-
schema.js
A Joi schema validator, this will be applied to the context before the view is rendered:
const Joi = require('joi'); module.exports = { val1: Joi.string().max(100), val2: Joi.string() };
_ example.js
A sample context and config in the form:
module.exports = [
{
_config: {
wrapStart: '<div class="container">',
wrapEnd: '</div>',
name: 'main'
},
val1 'example 1',
val2 'example 2'
},
{
val1 'example 1',
val2 'example 2'
}
];
-
path (required)
The path to search for modules
-
env
A nunjucks compile environment that will be passed to the nunjucks compile() method.
-
debug
When
true
this prints additional information when loading modules, default is false. -
log
A function that module-loader will use to print logging and debug information. Default is console.log().
A First + Third Project