【问题标题】:Templating solution for nested variables using nunjucks or other method使用 nunjucks 或其他方法的嵌套变量的模板解决方案
【发布时间】:2016-06-10 23:02:14
【问题描述】:

我刚刚开始使用 gulp 和 nunjucks 进行模板(在这种情况下是电子邮件)。

我想解决调用模块/部分并在每次处理时为属性分配不同值的问题。

它最初看起来像是一个 for 循环的工作,但不一定会在模板中按顺序调用该模块

在模块中有分配给变量的属性。 我想根据模块用于的部分以不同的方式解决这些变量。

一个非常基本的例子是 - 在一个索引文件中我有:

{% block content %}


<!-- logo start -->

{% include genericMod %}

<!-- logo end -->


<!-- some other section start -->

{% include someOtherMod %}

<!-- some other section end -->


<!-- hero start -->

{% include genericMod %}

<!-- hero end -->


{% endblock %}

而在 genericMod 本身-:

<tr>

 <td class="full-width-image" align="{{align}}" ><img src="{{src}}" alt="{{alt}}"/></td>

</tr>

我想利用的功能是定义一个“modKey”,即模块中每个变量中的一个变量 例如

{{modKey.align}}

{{modKey.src}}

{{modKey.alt}}

然后能够以某种方式在每次调用模块时将该键分配给模块:

<!-- logo start —>

{% include genericMod "modKey": "logo" %}

<!-- logo end -->

所以上面产生:

<tr>

 <td class="full-width-image" align="{{logo.align}}" ><img src="{{logo.src}}" alt="{{logo.alt}}"/></td>

</tr>

还有:

<!-- hero start -->

{% include genericMod "modKey": "hero" %}

<!-- hero end -->

产生:

<tr>

 <td class="full-width-image" align="{{hero.align}}" ><img src="{{hero.src}}" alt="{{hero.alt}}"/></td>

</tr>

因此,当通过 json 文件传输时,将为每个属性变量呈现相应的数据:

"logo": {
    "alt": "some logo alt text",
    "href": "http://www.someurl.com",
    "align": "left"
  },
 "hero": {
    "alt": "some hero alt text",
    "href": "http://www.someotherurl.com",
    "align": "centre"
  }

显然,这只是一个假设的解决方案,但有没有办法实际实现类似的目标?

【问题讨论】:

    标签: javascript npm gulp template-engine nunjucks


    【解决方案1】:

    事实证明,解决方案非常简单。尝试使用“set”时,我一直将上下文变量的值分配给字符串而不是变量名。

    为了记录,这是有效的......

    {% set data = logo %} 
    {% include oneIncludeFile %} 
    {% set data = hero %} 
    {% include otherIncludeFile %}
    

    包含文件将引用的位置,例如{{ data.alt }} 或 {{ data.href }}。

    虽然宏可能是实现这一目标的更好方法:

    {% macro foo(data) %} 
    <a href="{{ data.href }}"><img src="{{ data.src }}" alt="{{ data.alt }}" /></a> 
    {% endmacro %}
    

    然后像{{ foo(logo) }}{{ foo(hero) }} 一样调用它来传入不同的数据集。

    完整的解释可以在这里找到:https://github.com/mozilla/nunjucks/issues/779

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多