插值Django模板包含变量 [英] Interpolate Django template include variable

查看:118
本文介绍了插值Django模板包含变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一些类似

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

其中 inc.html 可能是这样的:

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

我刚刚发现前缀变量没有内插,part { forloop.counter0}} _在字面上传递。

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

任何比较优雅的解决方案?

Any relatively elegant work-around?

推荐答案

最好的解决方案是注册一个include_tag,它将处理部分和forloop.counter操作:

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

你可以这样称呼

{% 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 %}

这篇关于插值Django模板包含变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆