我想在每个部分之前和之后写一个 HTML 注释,带有部分的路径或名称,给将要实现它的人。
我可以获取页面的路径和文件名,但不能获取部分。你知不知道怎么?
我想在每个部分之前和之后写一个 HTML 注释,带有部分的路径或名称,给将要实现它的人。
我可以获取页面的路径和文件名,但不能获取部分。你知不知道怎么?
我想我现在明白你的意思了。
我把这个助手放在一起,让我知道它是否有帮助。
目前,帮助程序仅在部分之前添加注释,其中包含原始部分的路径 - 其中包括部分的名称。似乎还包括部分名称是多余的,因为它已经在路径中,但如果你想要,请在该 repo 上添加一个功能请求,我会添加它。我们也可以很容易地让它附加评论。
您可以使用以下方法安装帮助程序:
npm i handlebars-helper-partial
要让助手生成带有部分路径的 HTML 注释,您需要在 assemble 选项中定义以下内容(我这样做是为了使助手也可用于其他人):
assemble: {
options: {
include: {
origin: true
}
},
site: {
files: {}
}
}
或者,您可以添加一个名为的文件include.json
:
{
"include": {
"origin": true
}
}
然后在 Assemble 选项中指定该文件的路径:
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);
});
};