kno*_*ker 6 node.js express handlebars.js
我正在使用带有把手的expressjs作为模板引擎,在带有快速生成器的Webstorm IDE中使用以下代码.代码中没有可见的把手需要(我想快递生成器有它在其他地方不可见)
var app = express();
.
.
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
Run Code Online (Sandbox Code Playgroud)
在这种情况下,我如何在服务器端使用registerHelper?
我的其他渲染和部分工作正在工作.所以把手正在做它的工作.它只是那个registerHelper似乎引起了担忧.
Tom*_*m22 11
我对@Mukesh Sharma表示赞许,因为他几乎掌握了对我有用的语法,并真正将我引向了它。
我相信他会做更多工作以使其适用于前端。我需要的是以下内容
// index.js
//in the declarations
const exphbs = require('express-handlebars');
//when configuring the app view engine
app.engine('.hbs', exphbs({
extname: '.hbs',
helpers: require('./config/handlebars-helpers') //only need this
}));
app.set('view engine', '.hbs');
Run Code Online (Sandbox Code Playgroud)
然后,我有一个简单的文件,其中包含帮助者的内容。
// config/handlebars-helpers.js
module.exports = {
ifeq: function(a, b, options){
if (a === b) {
return options.fn(this);
}
return options.inverse(this);
},
bar: function(){
return "BAR!";
}
}
Run Code Online (Sandbox Code Playgroud)
无需传递或导入handlebars-express-包括helper函数的简单对象作为helper下exhbs options哈希的一部分,使express hbs可以通过自己的方法完成所有注册。
(奖金ifeq是一个比较两个参数的小助手,如果为true,则会显示该块。
class =“ {{#ifeq thisUrl'/ about'}} active {{/ ifeq}}” ..将导航药丸类设置为'active')在这里https://gist.github.com/pheuter/ 3515945
我认为express-generator只是设置view engine为hbs.要配置hbs引擎,您必须使用express-handlebars.
例如
var app = express(),
exphbs = require("express-handlebars");
app.engine("hbs", exphbs({
defaultLayout: "main",
extname: ".hbs",
helpers: require("./public/js/helpers.js").helpers, // same file that gets used on our client
partialsDir: "views/partials/", // same as default, I just like to be explicit
layoutsDir: "views/layouts/" // same as default, I just like to be explicit
}));
app.set("view engine", "hbs");
Run Code Online (Sandbox Code Playgroud)
并且,helpers.js
var register = function(Handlebars) {
var helpers = {
// put all of your helpers inside this object
foo: function(){
return "FOO";
},
bar: function(){
return "BAR";
}
};
if (Handlebars && typeof Handlebars.registerHelper === "function") {
// register helpers
for (var prop in helpers) {
Handlebars.registerHelper(prop, helpers[prop]);
}
} else {
// just return helpers object if we can't register helpers here
return helpers;
}
};
module.exports.register = register;
module.exports.helpers = register(null);
Run Code Online (Sandbox Code Playgroud)
资料来源:http://www.codyrushing.com/using-handlebars-helpers-on-both-client-and-server/
| 归档时间: |
|
| 查看次数: |
7138 次 |
| 最近记录: |