I'm trying to precompile a handlebar template in a node app. Later, I would like to store/retrieve the precompiled template to/from a database and use it.
var handlebars = require('handlebars');
var templateSpec = handlebars.precompile('{{foo}}');
var template = handlebars.template(templateSpec);
I base this code on the Handlebars reference.
The code above throws errors:
/home/ubuntu/workspace/handlebars/node_modules/handlebars/dist/cjs/handlebars/runtime.js:50
throw new _exception2['default']('Unknown template object: ' + typeof templateSpec);
^
Error: Unknown template object: string
at Object.template (/home/ubuntu/workspace/handlebars/node_modules/handlebars/dist/cjs/handlebars/runtime.js:50:11)
at HandlebarsEnvironment.hb.template (/home/ubuntu/workspace/handlebars/node_modules/handlebars/dist/cjs/handlebars.runtime.js:51:20)
at Object.<anonymous> (/home/ubuntu/workspace/handlebars/test.js:5:27)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Function.Module.runMain (module.js:441:10)
at startup (node.js:139:18)
at node.js:990:3
Not sure what I'm doing wrong.
This exact error is the topic of the following GitHub issue: https://github.com/handlebars-lang/handlebars.js/issues/1033
Precompile returns a string with the JavaScript source. It's not intended to be run in the same environment as you'd just use the compile method. If you do need to do this for some reason, you should eval this sting before passing to template.
The issue's author suggested the following alternative:
var preStr = Handlebars.precompile('{{foo}}');
var pre = (new Function('return ' + preStr)());
var template = Handlebars.template(pre);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With