1

我使用 Express-Handlebars 并想重构此代码示例以分隔文件

    const express = require('express');
    const exphbs = require('express-handlebars');

    const handlebars = exphbs.create({
        defaultLayout: 'index',
        extname: 'hbs',
        helpers: {
          foo: function () { // first helper
            return 'FOO!';
          },
          bar: function () { // second helper
            return 'BAR!';
          } 
          //, nth helper ...
        }
    });

原因是为什么要将所有 HTML 逻辑放入app.js文件中。我想为 1 个助手提供 1 个文件。

如何从外部文件注册助手?有人可以给我一个例子吗?

4

1 回答 1

2

尝试为每个助手创建一个模块,例如在helpers文件夹中:

助手/foo.js:

var foo = function () {
    return 'FOO!';
}

module.exports = foo;

助手/bar.js:

var bar = function () {
    return 'BAR!';
}

module.exports = bar;

应用程序.js:

const express = require('express');
const exphbs = require('express-handlebars');
const foo = require('helpers/foo');
const bar = require('helpers/bar');

const handlebars = exphbs.create({
    defaultLayout: 'index',
    extname: 'hbs',
    helpers: {
      foo: foo,
      bar: bar 
    }
});
于 2018-01-16T13:57:09.283 回答