javascript 如何使车把助手成为全球性的(在 expressjs 中)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32707322/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 15:38:29  来源:igfitidea点击:

How to make a handlebars helper global (in expressjs)

javascriptexpresshandlebars.jshelper

提问by n0pe

I've got a pretty simple handlebars helper file in helpers/handlebars.js:

我有一个非常简单的把手帮助文件helpers/handlebars.js

var hbs = require('express-handlebars');

hbs.registerHelper("inc", function(value, options) {
    return parseInt(value) + 1;
});

However, as expected, I can't refer to the {{#inc}}helper because I didn't pass it into the res.render()function. Is there a way to make all helpers in my file global and "auto-included"?

但是,正如预期的那样,我无法引用{{#inc}}helper,因为我没有将它传递给res.render()函数。有没有办法让我的文件中的所有助手成为全局和“自动包含”?

edit:

编辑:

After trying @1cgonza's awesome answer, I get:

尝试@1cgonza 的精彩回答后,我得到:

hbs.registerHelper("inc", function(value, options) {
      ^
TypeError: undefined is not a function

When running the app. Here's the app.js:

运行应用程序时。这是app.js

var engine      = require('express-handlebars');
                  require('./helpers/handlebars.js')(engine);

app.engine('hbs',           engine({defaultLayout: 'layout', extname: 'hbs'}));
app.set('view engine',      'hbs');

Any ideas?

有任何想法吗?

回答by 1cgonza

You could try exporting your helpers as a module and then include them in your main app.js

您可以尝试将您的助手导出为模块,然后将它们包含在您的主 app.js 中

Something like this:

像这样的东西:

In your helpers/handlebars.js

在你的 helpers/handlebars.js

function hbsHelpers(hbs) {
  hbs.registerHelper("inc", function(value, options) {
    return parseInt(value) + 1;
  });

  // More helpers...
}

module.exports = hbsHelpers;

Then in your app.js (or the file you are using as the index).

然后在您的 app.js(或您用作索引的文件)中。

var hbs = require('express-handlebars');
require('./helpers/handlebars')(hbs);

Does that work for you?

那对你有用吗?

EDIT

编辑

Based on the express-handlebarsdocs, I would change the function in your helpers/handlebars.jsto something like this:

根据express-handlebars文档,我会将您的功能更改为helpers/handlebars.js如下所示:

function hbsHelpers(hbs) {
  return hbs.create({
    helpers: { // This was missing
      inc: function(value, options) {
        console.log('reading it');
        return parseInt(value) + 1;
      }

      // More helpers...
    }

  });
}

module.exports = hbsHelpers;

Let us know if it works.

让我们知道它是否有效。

EDIT 2:

编辑2:

My Bad, wrapping your helpers inside a helpers:{}was missing from the create()function in the handelbars.jsfile. I've edited my previous answer, see where I placed the comment to know what I am talking about.

我的错,文件中helpers:{}create()函数缺少将您的助手包装在 a中handelbars.js。我已经编辑了我之前的答案,请查看我发表评论的位置以了解我在说什么。

As for the app.jsI think it is a little mixed up, so let me rename a few things to make it clear:

至于app.js我觉得有点混淆,所以让我重命名一些东西来清楚说明:

// I've changed this from engine to exphbs,
// so there is no confusion with the express engine object that we use later.
var exphbs = require('express-handlebars');

// Create an instance of the express-handlebars
// If you want to pass any option offered by express-handlebar module
// do it inside the create() in the handlebars.js file
var handlebars  = require('./helpers/handlebars.js')(exphbs);

// The handlebars variable now has an object called engine.
// Use that to define your app.engine
// As said before, you don't need to define any options here.
// Everything is defined in the create() in handlebars.js
app.engine('hbs', handlebars.engine);

// If you are using a different extension, you can change hbs to whatever you are using. 
app.set('view engine', 'hbs');

回答by IT Vlogs

you can try:

你可以试试:

in helpers/handlebars.js:

在 helpers/handlebars.js 中:

var register = function(Handlebars) {
    var helpers = {
    inc: function(value, options) {
        return parseInt(value) + 1;
    },
    foo: function(var1, var2) {
        return ....
    }
};

if (Handlebars && typeof Handlebars.registerHelper === "function") {
    for (var prop in helpers) {
        Handlebars.registerHelper(prop, helpers[prop]);
    }
} else {
    return helpers;
}

};

module.exports.register = register;
module.exports.helpers = register(null); 

in app.js:

在 app.js 中:

var exphbs = require('express-handlebars');
var hbsHelpers = exphbs.create({
    helpers: require("./helpers/handlebars.js").helpers,
    defaultLayout: 'layout',
    extname: '.hbs'
});

app.engine('.hbs', hbsHelpers.engine);
app.set('view engine', '.hbs');

回答by David Dehghan

Here is my solution. You can register both your own customer helpers and the ones from 'handlebars-helpers':

这是我的解决方案。您可以注册自己的客户助手和来自“handlebars-helpers”的客户助手:

const hbshelpers = require('handlebars-helpers');
const multihelpers = hbshelpers();

const helpersDM = {
    hlp: echo => `Echo: ${echo}.`,
    STATIC: `/static`,
};
const hbs = exphbs.create({
    layoutsDir: join(__dirname, 'views', 'layouts'),
    partialsDir: join(__dirname, 'views', 'partials'),
    extname: '.hbs',
    defaultLayout: 'base',
    helpers: {...multihelpers, ...helpersDM},
});
app.engine('.hbs', hbs.engine);
app.setViewEngine('.hbs');