gpt4 book ai didi

node.js - 使用 Expressjs 的 Handlebars registerHelper 服务器端

转载 作者:搜寻专家 更新时间:2023-10-31 22:36:18 24 4
gpt4 key购买 nike

我在带有 express 生成器的 Webstorm IDE 中使用带有 handlebars 的 expressjs 作为模板引擎,并使用以下代码。代码中没有可见的 handlebars 要求(我猜 express 生成器在其他不可见的地方有它)

var app = express();
.
.
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');

在这种情况下,我如何在服务器端使用 registerHelper?

我的其他效果图和局部效果都在工作。所以 handlebars 正在做它的工作。只是 registerHelper 似乎是令人担忧的原因。

最佳答案

我对@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');

然后我有一个简单的文件,我从中包含了一些帮助内容。

// 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!";
}
}

无需传递或导入 handlebars-express - 将辅助函数的简单对象作为 exhbs 选项散列的一部分包含在 helpers 下,让 express hbs 通过它自己的方法完成所有注册。

(Bonus ifeq is a tiny helper that compares two arguments and will show the block if true .. useful for something like:

class = "{{#ifeq thisUrl '/about'}}active{{/ifeq}}" .. to set a nav pill class as 'active' )found it here https://gist.github.com/pheuter/3515945

关于node.js - 使用 Expressjs 的 Handlebars registerHelper 服务器端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41423727/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com