4

I have a top-level template where I want to use a "fragment" template inside a for cycle but I'm not able to pass in the variable value:

  {% for item in coll %}
    {% include "fragment.html" with name="slack" item=item %}
  {% endfor %}

item and name is then used in the fragment.html template:

<div>
  <label>
    <input
      title="{{item.id}}"
      id="{{name}_{{item.id}}_active"
      name="{{name}}-{{item.id}}_active"
...
    />

While the name parameter is expanded properly (its value is hardcoded in the parent template), the item parameter is not (its value is passed in as is).

Do I need to use a different syntax for that or it's just not supported?

Juraj Martinka
  • 3,991
  • 2
  • 23
  • 25

1 Answers1

2

The include tag splices in the included template. This means that any variables within scope of the parent template will be available to the included template. The with operator allows you to supply default values, which are not interpreted. Saying item=item is effectively saying item|default:"item", which is to say that item is redefined as "item".

See https://github.com/yogthos/Selmer#including-templates

Jeremy
  • 22,188
  • 4
  • 68
  • 81
  • Great, thanks for clarification. I've found this myself experimentally. Indeed, the `width` tag is what I reached for. – Juraj Martinka Oct 06 '20 at 06:19
  • I messed around a little more, and I'm not entirely sure why the literal string "item" was being passed through for you. For me it's passing through the value of the `item` variable. Regardless, you don't need to say `item=item` anyway! – Jeremy Oct 06 '20 at 16:42
  • Oh yeah, and it's really just confusing to pass it explicitly since it always takes the value of the `item` variable from the outer scope anyway. So it's best to left it out and just use `with` in the surrounding context. – Juraj Martinka Oct 07 '20 at 03:33