0

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?

hap497
  • 154,439
  • 43
  • 83
  • 99

1 Answers1

0

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 %}
Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • i tried your solution above. But it does not work for me, it seems it can't resolve 'property1' in some logic.stencil despite I passed in 'p' as context. – hap497 Oct 09 '20 at 19:05