Node / Express Handlebars - Where to define custom helpers

落爺英雄遲暮 提交于 2019-12-24 01:45:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!