如何使用不同的变量名称调用 swift 中的 Stencil?
How to call a Stencil in swift with different variable name?
我有2个模版模板,除了变量名不同外几乎一样:
模板 #1
{% for p in anArray %}
{% if p.property1 = "abc" %}
// some logic
{% endif %}
{% endfor %}
模板 #2
{% for a in aDifferentNameArray %}
{% if a.property1 = "abc" %}
// same logic as template 1
{% endif %}
{% endfor %}
我认为如果我可以将其重构为一个模板并让模板 #1 和 #2 调用这个新模板,它会更清晰
{% if ??.property1 = "abc" %}
// same logic as template 1
{% endif %}
但问题出在模板 #1 中,变量是 p
,而在模板 #2 中,变量是 a
。
那么我该如何调用具有不同变量名的模板#1 和#2 的新模板呢?
这正是 include
标签的用例。使用此标记,您可以包含另一个模板的内容,还可以将其传递给您选择的上下文。
将 some logic
移动到单独的模板。我们称该文件为 some logic.stencil
。在那里,无论你在哪里使用 p.propertyX
,你都应该将它更改为 propertyX
,因为你给它 p
/a
作为上下文。
一些logic.stencil:
{% if property1 = "abc" %}
{# same logic as template 1, except all the "p." are deleted. #}
{% endif %}
在模板 #1 中,执行:
{% for p in anArray %}
{% include "some logic.stencil" p %} {# passing "p" as the context #}
{% endfor %}
在模板 #2 中,执行:
{% for a in aDifferentNameArray %}
{% include "some logic.stencil" a %} {# passing "a" as the context #}
{% endfor %}
我有2个模版模板,除了变量名不同外几乎一样:
模板 #1
{% for p in anArray %}
{% if p.property1 = "abc" %}
// some logic
{% endif %}
{% endfor %}
模板 #2
{% for a in aDifferentNameArray %}
{% if a.property1 = "abc" %}
// same logic as template 1
{% endif %}
{% endfor %}
我认为如果我可以将其重构为一个模板并让模板 #1 和 #2 调用这个新模板,它会更清晰
{% if ??.property1 = "abc" %}
// same logic as template 1
{% endif %}
但问题出在模板 #1 中,变量是 p
,而在模板 #2 中,变量是 a
。
那么我该如何调用具有不同变量名的模板#1 和#2 的新模板呢?
这正是 include
标签的用例。使用此标记,您可以包含另一个模板的内容,还可以将其传递给您选择的上下文。
将 some logic
移动到单独的模板。我们称该文件为 some logic.stencil
。在那里,无论你在哪里使用 p.propertyX
,你都应该将它更改为 propertyX
,因为你给它 p
/a
作为上下文。
一些logic.stencil:
{% if property1 = "abc" %}
{# same logic as template 1, except all the "p." are deleted. #}
{% endif %}
在模板 #1 中,执行:
{% for p in anArray %}
{% include "some logic.stencil" p %} {# passing "p" as the context #}
{% endfor %}
在模板 #2 中,执行:
{% for a in aDifferentNameArray %}
{% include "some logic.stencil" a %} {# passing "a" as the context #}
{% endfor %}