Interpolate Django template include variable

放肆的年华 提交于 2019-12-22 10:05:54

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!