【问题标题】:Rendering template within context in Handlebars在 Handlebars 的上下文中渲染模板
【发布时间】:2016-12-12 08:13:13
【问题描述】:

是否可以从传递给顶级模板的上下文中渲染模板,甚至只是部分模板?看起来这可能需要递归渲染,但也许我遗漏了一些东西。

下面的示例使用 Bootstrap 演示了这一点。

说这是我的顶级模板:

<div class="panel">
  <div class="panel-body">
    {{{description}}}
  </div>
</div>

我的上下文是:

{
  description: "\
    Some text before the warning.\

    <div class=\"alert alert-warning\" role=\"alert\">\
      <span class=\"glyphicon glyphicon-warning-sign\" aria-hidden=\"true\">&nbsp;</span>\
      My warning here.\
    </div>\

    Some text after the warning."
}

出于多种原因,我想做的是将警报分成部分:

  • 在周围文本中任意放置
  • 可以为警告以外的类型(危险、信息等)制作部分内容
  • 可以根据需要添加任意数量的散布在上下文字符串中

由于这些原因,似乎无法将其放入顶级模板中。

部分看起来像这样:

<script id="partial-warning-template" type="text/x-handlebars-template">
  <div class="alert alert-warning" role="alert">
    <span class="glyphicon glyphicon-warning-sign" aria-hidden="true">&nbsp;</span>
    {{{warning-message}}}
  </div>
</script>

一旦到位,我就可以像这样使用它:

{
  description: "\
    Some text before the warning.\

    {{> partial-warning-template \"My warning here.\"}}\

    Some text after the warning.\

    {{> partial-warning-template \"Now adding a second warning.\"}}"
}

也许我遗漏了一些基本的东西 - 有没有更惯用的方法来做到这一点?

【问题讨论】:

    标签: handlebars.js


    【解决方案1】:

    您将无法在 description 值中包含部分块,并期望它们被顶级模板方法评估为部分;整个 description 字符串将作为单个文字字符串吐出。

    您需要做的是在将带有description 的上下文对象传递给顶级模板方法之前对部分进行评估。

    如果您以如下方式预编译了您的部分:

    Handlebars.registerPartial('warn', Handlebars.compile(document.getElementById('partial-warning-template').innerHTML));
    

    然后你就可以在构造 description 字符串时调用这个部分:

    {
        description: 'Some text before the warning.' +
                  Handlebars.partials.warn({ 'warning-message': 'My warning here.' }) +
                  'Some text after the warning.' +
                  Handlebars.partials.warn({ 'warning-message': 'Now adding a second warning.' })
    }
    

    【讨论】:

    • 谢谢!作为参考,我将编译后的模板分配给标准函数,而不是污染部分对象,但效果相同。 let warn = Handlebars.compile($("#partial-warning-template").html());后来“警告前的一些文字。” + warn(“我的警告在这里。”) +“警告后的一些文字” + warn(“现在添加第二个警告。”);我的模板有 {{{this}}} 作为内部内容。
    猜你喜欢
    • 2013-01-27
    • 1970-01-01
    • 2011-11-02
    • 2012-09-08
    • 2013-01-22
    • 1970-01-01
    • 2014-07-05
    • 2020-11-29
    • 1970-01-01
    相关资源
    最近更新 更多