我想在每个部分之前和之后写一个HTML注释,其中包含部分的路径或名称,以及将要实现它的人。
我可以获取页面的路径和文件名,但不能获取部分路径和文件名。你知道吗?
答案 0 :(得分:1)
我想我现在知道你的意思了。
我把this helper放在一起,让我知道它是否有帮助。
目前,帮助程序仅在partial之前添加注释,其中包含原始partial的路径 - 其中包含partial的名称。似乎多余的也包括部分的名称,因为它已经在路径中,但如果你想要那个请在该回购添加一个功能请求,我会添加它。我们也可以轻松地附加评论。
您可以使用以下命令安装帮助程序:
npm i handlebars-helper-partial
要让帮助程序生成带有partial的路径的HTML注释,您需要在汇编选项中定义以下内容(我这样做是为了使帮助程序也可用于其他人):
assemble: {
options: {
include: {
origin: true
}
},
site: {
files: {}
}
}
或者,您只需添加名为include.json
的文件:
{
"include": {
"origin": true
}
}
然后在“汇编”选项中指定该文件的路径:
assemble: {
options: {
data: ['include.json', 'other/files/*.json']
},
site: {
files: {}
}
}
以下是帮助程序的完整代码:
/**
* Handlebars Helpers: {{include}}
* Copyright (c) 2013 Jon Schlinkert
* Licensed under the MIT License (MIT).
*/
var path = require('path');
var _ = require('lodash');
var yfm = require('assemble-yaml');
// Export helpers
module.exports.register = function (Handlebars, options, params) {
'use strict';
var assemble = params.assemble;
var grunt = params.grunt;
var opts = options || {};
/**
* {{partial}}
* Alternative to {{> partial }}
*
* @param {String} name The name of the partial to use
* @param {Object} context The context to pass to the partial
* @return {String} Returns compiled HTML
* @xample: {{partial 'foo' bar}}
*/
Handlebars.registerHelper('include', function(name, context) {
if(!Array.isArray(assemble.partials)) {
assemble.partials = [assemble.partials];
}
var filepath = _.first(_.filter(assemble.partials, function(fp) {
return path.basename(fp, path.extname(fp)) === name;
}));
// Process context, using YAML front-matter,
// grunt config and Assemble options.data
var pageObj = yfm.extract(filepath) || {};
var metadata = pageObj.context || {};
// `context` = the given context (second parameter)
// `metadata` = YAML front matter of the partial
// `opts.data[name]` = JSON/YAML data file defined in Assemble options.data with a basename
// matching the name of the partial, e.g {{partial 'foo'}} => foo.json
// `this` = YAML front matter of _either_ the "inheriting" page, or a block
// expression wrapping the helper
// `opts` = Custom properties defined in Assemble options
// `grunt.config.data` = Data from grunt.config.data (e.g. pkg: grunt.file.readJSON('package.json'))
context = _.extend({}, grunt.config.data, opts, this, opts.data[name], metadata, context);
context = grunt.config.process(context);
var template = Handlebars.partials[name];
var fn = Handlebars.compile(template);
var output = fn(context).replace(/^\s+/, '');
// Prepend output with the filepath to the original partial
opts.data.include = opts.data.include || {};
if(opts.data.include.origin === true) {
output = '<!-- ' + filepath + ' -->\n' + output;
}
return new Handlebars.SafeString(output);
});
};