4

I'm doing something like

{% for part in parts %}
     {% include "inc.html" with o=part prefix="part{{ forloop.counter0 }}_" %}
{% endfor %}

where inc.html could be something of such kind:

<p id="{{ prefix }}para">{{ o.text }}</p>

I just discovered the prefix variable isn't interpolated and "part{{ forloop.counter0 }}_" is passed literally.

Any relatively elegant work-around?

Guard
  • 6,816
  • 4
  • 38
  • 58
  • Why do people think you can use variable syntax *inside* templatetags? There's nothing in the documentation to suggest this. – Daniel Roseman Sep 27 '11 at 19:28
  • 7
    because it **would** be so natural! is my example so silly and stupid? it's a real world example, I'm using this inclusion in 2 other places with plain string prefixes and now I need it inside a loop - nothing theoretical, just a regular expectation – Guard Sep 27 '11 at 19:35

1 Answers1

4

I think the best solution would be to register an inclusion_tag, that would handle the part and forloop.counter operations:

@register.inclusion_tag("inc.html")
def inc_tag(part, loop_counter):
    prefix = 'part%s_' % (loop_counter,)
    context = {
        'part': part,
        'prefix': prefix,
    }
    return context

And you would call it like that

{% for part in parts %}
    {% inc_tag part=part loop_counter=forloop.counter0 %}
{% endfor %}

Your way is also doable like so, but I wouldn't recommend that

{% for part in parts %}
    {% with "part"|add:forloop.counter0|add:"_" as prefx %}
        {% include "inc.html" with o=part prefix=prefix %}
    {% endwith %}
{% endfor %}
Ania Warzecha
  • 1,796
  • 13
  • 26
  • your 2nd solution fails probably because of "This filter will first try to coerce both values to integers. If this fails, it'll attempt to add the values together anyway. This will work on some data types (strings, list, etc.) and fail on others. If it fails, the result will be an empty string." Going to experiment with the 1st one now – Guard Sep 27 '11 at 19:39