问题
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?
回答1:
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 %}
来源:https://stackoverflow.com/questions/7574323/interpolate-django-template-include-variable