Dynamic Data
There are two ways you can pass data dynamically to the templates on every page request:
- onPageRequest engine option
- On custom express route page request
On Page Request
One of the engine options is the onPageRequest which must be a function that is called on every page request with the express request object and must return an object to be used as the data in the template.
const {engine} = require('@beforesemicolon/html-plus');
const app = express();
engine(app, path.resolve(__dirname, './pages'), {
onPageRequest: (req) => {
return {
path: req.path,
params: req.params
}
}
});
This data can be accessed inside the template as you keyed them in the object.
<p>Page path is {path} with params {params}</p>
On Express Route Request
You can also setup dynamic custom routes to handle page requests which will give you the opportunity to call the express response render method to render a particular template.
This render method also takes a second argument which is the object data to be passed to the template.
app.get('/projects/:projectName', (req, res) => {
res.render('projects/project', {
projectName: req.params.projectName.replace('-', ' '),
title: 'Projects'
})
});
<h2>{title}</h2>
<h3>Welcome to "{projectName}" project</h3>
Both options to inject data into templates are great ways to collect data from any data storage source and handle it right inside the templates so it is composed right inside the templates.