节点/Express把手-定义自定义帮助器的位置 [英] Node / Express Handlebars - Where to define custom helpers

查看:70
本文介绍了节点/Express把手-定义自定义帮助器的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个node/express/handlebars应用程序,我刚刚发现了有关自定义帮助程序的信息,但是我不知道在哪里定义它们.

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.

我尝试在<script>标签中的实际视图模板hbs文件中添加一些内容,如下所示:

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>

但是我遇到了一个Uncaught ReferenceError:未定义车把.

But I get a Uncaught ReferenceError: Handlebars is not defined.

我还找到了 JSFiddle ,但是我的应用程序中没有类似该代码的内容.我也看过许多教程,但是他们几乎说出了官方文档中完全相同的内容.

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.

那么我该在节点/express应用中的确切位置包含此代码吗?

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.

我不确定这是否正确,但是您可以在设置视图引擎后将其放入app.js:

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.

推荐答案

我个人在根目录中创建了一个helpers文件夹,并将所有我的helper方法放在其中.然后,您可以要求进入app.js并告诉hbs引擎您要将该文件用作帮助程序.

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
});

这篇关于节点/Express把手-定义自定义帮助器的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆