Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

160
Views
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?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!