假设我有一个网站,每个主要部分都有一个特定的侧边栏。
目前我有一个侧边栏文件,我使用类别来过滤正确的内容,如下所示:
{{#inArray page.categories "Components"}}
<section class="sg-index">
<ul>
<li {{#is title "DetailContent"}} class="active"{{/is}}>
<a href="c-DetailContent.html">DetailContent</a>
</li>
但是我的目标是让这些侧边栏文件与部分文件一起位于每个部分文件夹中。
如何在partials调用中{{dirname}}变量{{&gt;侧边栏}}?
答案 0 :(得分:1)
这应该可以使用条件块帮助程序,例如{{with}}
和include helper,
B你也可以创建一个自定义助手,如下所示:
var path = require('path');
var _ = require('lodash');
var matter = require('gray-matter');
module.exports.register = function (Handlebars, options, params) {
var assemble = params.assemble;
var grunt = params.grunt;
var opts = options || {};
Handlebars.registerHelper('sidenav', function(page, context) {
if(page.published !== false && page.sidenav) {
if(!Array.isArray(assemble.partials)) {
assemble.partials = [assemble.partials];
}
var filepath = _.first(_.filter(assemble.partials, function(fp) {
return path.basename(fp, path.extname(fp)) === page.sidenav;
}));
// Process context, using YAML front-matter,
// grunt config and Assemble options.data
var pageObj = matter(filepath) || {};
var metadata = pageObj.context || {};
context = _.extend(this, opts.data[page.sidenav], metadata, context);
var partial = Handlebars.partials[page.sidenav];
var template = Handlebars.compile(partial);
var output = template(context);
// Prepend output with the filepath to the original partial
// for debugging
var sidenav = opts.sidenav || opts.data.sidenav || {};
if(sidenav.origin === true) {
output = '<!-- ' + filepath + ' -->\n' + output;
}
return new Handlebars.SafeString(output);
}
});
};
然后在你的标记中使用它:
<div class="sidebar" role="complementary">
<ul class="nav sidenav">
{{sidenav this}}
</ul>
</div>