How to call a Stencil in swift with different variable name?

375 views Asked by At

I have 2 stencil templates, which pretty much the same except the variable name is different:

template #1

{% for p in anArray %}
  {% if p.property1 = "abc" %}
    // some logic
  {% endif %}
{% endfor %}

template #2

{% for a in aDifferentNameArray %}
  {% if a.property1 = "abc" %}
    // same logic as template 1
  {% endif %}
{% endfor %}

I think it will be cleaner if I can refactor this into a template and have template #1 and #2 call this new template

  {% if ??.property1 = "abc" %}
    // same logic as template 1
  {% endif %}

But problem is in template #1, the variable is p where as in template #2, the variable is a. So what can i do to call the new template with template #1 & #2 with different variable name?

1

There are 1 answers

1
Sweeper On BEST ANSWER

This is exactly the use case for the include tag. Using this tag, you can include the contents of another template, and also pass it a context of your choice.

Move some logic to a separate template. Let's call that file some logic.stencil. In there, wherever you have used p.propertyX, you should change it to just propertyX, since you are giving it p/a as the context.

some logic.stencil:

{% if property1 = "abc" %}
    {# same logic as template 1, except all the "p." are deleted. #}
{% endif %}

In template #1, do:

{% for p in anArray %}
    {% include "some logic.stencil" p %} {# passing "p" as the context #}
{% endfor %}

In template #2, do:

{% for a in aDifferentNameArray %}
    {% include "some logic.stencil" a %} {# passing "a" as the context #}
{% endfor %}