【问题标题】:Node / Express Handlebars - Where to define custom helpersNode / Express Handlebars - 在哪里定义自定义助手
【发布时间】:2016-12-04 07:36:52
【问题描述】:

我正在开发一个节点/快递/车把应用程序,我刚刚发现了自定义助手,但我不知道在哪里定义它们。

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

<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>

但我得到一个未捕获的 ReferenceError: Handlebars is not defined.

我还发现了这个JSFiddle,但我的应用程序中没有任何类似该代码的内容。我也看过十几个教程,但他们说的几乎和官方文档一样。

那么我在节点/快递应用程序中究竟应该在哪里包含此代码?

如果有人能对这个问题有所了解,将不胜感激。

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

var hbs = require('hbs');

hbs.registerHelper('test', function(conditional, options) {
  //do something
  if (conditional) {
    return options.fn(this);
  } else {
    return options.inverse(this);
  }
});

如果由于某种原因这不正确或有问题,请告诉我。

【问题讨论】:

  • 如果在服务端渲染,需要在服务端设置。

标签: node.js express handlebars.js


【解决方案1】:

这个解决方案对我有用。

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

【讨论】:

    【解决方案2】:

    我个人在根目录中创建了一个 helpers 文件夹,并将我所有的辅助方法都放在那里。然后,您可以 require 到您的 app.js 中并告诉 hbs 引擎您想将该文件用于帮助程序。

    // in app.js
    
    const hbsHelpers = require('./helpers/handlebars');
    ...
    app.engine('handlebars', exphbs({
      helpers: hbsHelpers
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-27
      • 1970-01-01
      • 2023-03-30
      • 2018-05-14
      • 2015-10-23
      • 1970-01-01
      • 2013-08-03
      • 2016-06-09
      相关资源
      最近更新 更多