'Output Handlebars template from a helper
I use Handlebars as a sub-project within my bigger Webpack project. There is a single HBS template, combined with couple of different data/JSON sources to prebuild various HTML templates, required in other parts of the project. I build them manually, using an npm script and handlebars-webpack-plugin.
What I need, are kind of "data-driven partials". This means I need to insert a specific partial according to the given data value. I.e. if the data sources go like:
// dev.json:
{
"header_css": "styles/devel/header.css"
}
// prod.json:
{
"header_css": "prod/header.css"
}
then in the HBS template I'd need something like:
{{#import header_css }}
which should be replaced by the respective CSS file. I couldn't find anything similar to #import in Handlebars, so I created a custom helper:
// webpack.config.js:
...
new HandlebarsPlugin({
...
helpers: {
"import": require("./src/hbs/helpers/import.js"),
}
})
// import.js:
...
const fs = require("fs")
module.exports = (par) => {
return fs.readFileSync(path + par)
}
It works fine. Though, the content of the linked file is placed as is. It's useful in some cases, but I also need to import Handlebars partials the same way sometimes, so that they are compiled. If I create i.e.:
// partials/heading.hbs:
<h1>{{title}}</h1>
and then I use:
// data.json:
{
"title": "My Title."
}
// template.hbs:
<body>
{{> partials/heading.hbs}}
the content of heading is loaded, processed and compiled as a Handlebars template:
<body>
<h1>My Title.</h1>
But if I import it using the helper:
// data.json
{
"title": "partials/heading.hbs"
}
// template.hbs
<body>
{{#import title}}
...
it's not compiled and the output contains the Handlebars source code:
<body>
<h1>{{title}}</h1>
The question is, how can I make the {{title}} from the imported file to be compiled as well?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
