Is there a protocol for loading pre-compiled templates using handlebars.js NPM module or one has to supply their own “getTemplate” function to load a specific template ?
Following fails with a cannot read property 'hello' of undefined.
var compiledTemplate = handlebars.templates['hello'];
“hello.handlebars“ is name of the template file.
whereas this one works fine.
var template = fs.readFileSync(“./hello.html", "utf8");
var uncompiledTemplate = handlebars.compile(template);
var data = {message : "Hello world!"};
var finalPageHTML = uncompiledTemplate(data);
So what do I need so I can just execute
compiledTemplate(data)
and get my final HTML simmilar to the uncompiled version ?
Thanks.
I found a solution that works for me. I have a template in my templates directory, called list.handlebars:
<ul>
<li>{{title}}</li>
</ul>
Then, I run this command:
handlebars -c handlebars templates -f dist/templates.js && echo module.exports = templates; >> dist/templates.js
The '-c handlebars' flag prepends require("handlebars"); to the output.
Then, in my server code, i use:
var template = require('./dist/templates');
console.log(template['list']({title: 'winner'}));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.