我刚刚开始使用 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}}
然后能够在每次调用模块时以某种方式将该 key 分配给模块:
<!-- 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"
}
显然这只是一个假设的解决方案,但有没有办法真正实现类似的目标?
最佳答案
事实证明解决方案非常简单。当尝试使用“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
关于javascript - 使用 nunjucks 或其他方法的嵌套变量的模板解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37725129/