问题
I'm working on a node / express / handlebars app and I just found out about custom helpers, but I have no idea where to define them.
I tried adding some in the actual view template hbs file in a <script> tag like so:
<script type="text/javascript">
Handlebars.registerHelper('if', function(conditional, options) {
console.log("IN HANDLEBARS HELPER");
if (conditional) {
return options.fn(this);
} else {
return options.inverse(this);
}
});
</script>
But I get a Uncaught ReferenceError: Handlebars is not defined.
I also found this JSFiddle, but I don't have anything that looks like that code in my app. I've also looked at a dozen tutorials but they pretty much say the exact same thing the official documentation does.
So where do I include this code in the node / express app exactly?
If anyone can shed some light on this issue, it would be appreciated.
EDIT: I'm not sure if this is the right way, but you can put it in your app.js after you have set the view engine:
var hbs = require('hbs');
hbs.registerHelper('test', function(conditional, options) {
//do something
if (conditional) {
return options.fn(this);
} else {
return options.inverse(this);
}
});
If this is incorrect or problematic for some reason, please let me know.
回答1:
I personally create a helpers folder in the root directory and put all my helper methods in there. You can then require into your app.js and tell the hbs engine that you want to use that file for helpers.
// in app.js
const hbsHelpers = require('./helpers/handlebars');
...
app.engine('handlebars', exphbs({
helpers: hbsHelpers
});
回答2:
this solution work for me.
inside app.js
below
app.set('view engine', 'hbs');
//example get local date
var hbs = require('hbs');
hbs.registerHelper('dateLocal', function(fecha) {
return new Date(fecha).toLocaleDateString();
});
来源:https://stackoverflow.com/questions/38661295/node-express-handlebars-where-to-define-custom-helpers