nodejs+express4.x+express-hbs开发时, express-hbs如何实现动态加载子模板(局部视图)?
我想实现的效果是根据不同页面使用不同的局部视图,当然是有条件判断的 类似下面的逻辑.
{{#if xxx==‘1’}} {{>zhengquan_channel}} {{else if xxx==‘2’}} {{>qiche_channel}} {{/if}}
当然上面的代码是错误的.我就是不知道语法,也不知道怎么能实现!希望知道的朋友不吝赐教.非常感谢了...急着写这个功能!
如果你的layout 文件夹下面,有一个hbs叫做index.hbs, 可以这么写
<body>
<div >公共的视图</div>
{{{body}}}
</body>
在
app.get('/user', function(req,res) {
res.render('user', layout: 'index')
})
指定layout 用哪个
在user.hbs中写的页面代码,就是你的局部视图,会渲染到那个{{{body}}}所占的地方, 最后访问/user这个url的时候,公共视图有了,局部视图也有了,
@liujavamail 局部视图{{>head}}类似这样就可以引入啊...我现在就是想动态的更换这个局部视图...根据用户访问的页面的不同(实际上这些页面是用的一个模板),而这个模板里面我引入了{{>head}}这个局部视图,当用户传参数不同,比如u=1时,用{{>head}},u=2时{{>head_2}},u=3时{{>head_3}}......
页面对应的模板一直没变,就是局部视图哪里改变了!
app.engine(‘hbs’, exphbs.express4({ partialsDir: ‘./views/template/partials/’, //模版文件的绝对路径 layoutsDir: "./views/template/layouts/", defaultLayout:’./views/template/layouts/layout-default’, extname: ‘.hbs’, helpers: { section: function(name, options) { if(!this._sections) this._sections = {}; this._sections[name] = options.fn(this); console.log(name,options) return null; } }
}));
@liujavamail 我使用的是express-hbs,跟express-Handlebars功能是一样的吧?,我helpers是按照你给的地址设置的.为什么提示500错误.我可能是哪里配置错误了...能看下我的代码吗?
https://github.com/barc/express-hbs
你用的是这个吗?
hbs.registerHelper('link', function(text, options) {
var attrs = [];
for(var prop in options.hash) {
attrs.push(prop + '="' + options.hash[prop] + '"');
}
return new hbs.SafeString(
"<a " + attrs.join(" ") + ">" + text + "</a>"
);
});
# in markup
{{{link 'barc.com' href='http://barc.com'}}}
好像是要registerHelper
试一试,如果你自己定义一个标签,是否还会有用,类似于angular.js的directive hbs.registerHelper(‘mydiv’, function() {})
{{{mydiv }}}