自定义Handlebars Helper with partial作为哈希参数

时间:2014-07-11 12:16:14

标签: node.js handlebars.js assemble

我正在尝试创建一个自定义手柄帮助器,我希望能够将它传递给“基本模板”和“部分”..

那么它应该做的是呈现基本模板,然后渲染作为第二个参数传递的任何部分。

我现在有以下内容:

module.exports.register = function(Handlebars, options) {

  var assembleOpts = options || {};

  Handlebars.registerHelper("sgComponent", function (template, partial, options) {

  // Default options
  var opts = {
    cwd: '',
    src: '',
    glob: {}
  };

  options = _.defaults(options.hash, assembleOpts.sgComponent, opts);

  var partialContent, partialContext;

  // Join path to 'cwd' if defined in the helper's options
  var cwd = path.join.bind(null, options.cwd, '');
  var src = path.join.bind(null, options.src, '');

  glob.find(src(partial), options.glob).map(function(path) {
    partialContext = yfm.extract(path).context;
    partialContent = yfm.extract(path).content;
  });

  return glob.find(cwd(template), options.glob).map(function(path) {
    var context = yfm.extract(path).context;
    var content = yfm.extract(path).content;

    return {
      path: path,
      context: processContext(grunt, partialContext),
      content: content
    };
  }).map(function (obj) {
    var template = Handlebars.compile(obj.content);
    return new Handlebars.SafeString(template({content: obj.context}));
  });
});

var processContext = function(grunt, context) {
  grunt.config.data = _.defaults(context || {}, _.cloneDeep(grunt.config.data));
  return grunt.config.process(grunt.config.data);
};

};

现在我正在使用这样的助手:

{{{sgComponent 'path/to/basetemplate/basetemplate.hbs' 'path/to/partial/partial.hbs'}}}

我现在有点卡住了。目前我只能弄清楚如何渲染基本模板或部分..或渲染基本模板,但使用部分上下文(它的yaml字体问题)我想要实现的是渲染的basetemplate和部分内容在其内部呈现,具有在部分中定义的任何上下文。

像这样(基本模板):

<div class="sg-component">
  <!-- Markup -->
  <div class="sg-component__markup">
   {{partial}}
  </div>

  <!-- Documentation -->
  <div class="sg-component__documentation">
  {{#markdown}}
    ~~~markup
    {{partial}}
    ~~~
  {{/markdown}}
  </div>
</div>

部分:

---
context: context stuff here
---

<h1 class="title--huge"><a href="#">This is a very large header</a></h1>
<h2 class="title--xlarge"><a href="#">This is a large header</a></h2>
<h3 class="title--large"><a href="#">This is a medium header</a></h3>
<h4 class="title--medium"><a href="#">This is a moderate header</a></h4>
<h5 class="title--small"><a href="#">This is a small header</a></h5>
<h6 class="title--xsmall"><a href="#">This is a tiny header</a></h6>

提前致谢! 丹

1 个答案:

答案 0 :(得分:0)

所以,我把它修好了!乌拉..

我坐下来思考它,得出的结论是我只需要将第二个哈希参数注册为部分哈希。

所以我在Handlebars.compile(obj.content);

之后添加了这个
Handlebars.registerPartial("sgComponentContent", partial);

然后在我的basetemplate中,我现在可以使用{{> sgComponentContent}}

真棒!

相关问题