如何将forloop.counter连接到我的django模板中的字符串

Eth*_*han 19 python django for-loop string-concatenation django-templates

我已经尝试连接这样的:

{% for choice in choice_dict %}
    {% if choice =='2' %}
        {% with "mod"|add:forloop.counter|add:".html" as template %}
            {% include template %}
        {% endwith %}                   
    {% endif %}
{% endfor %}    
Run Code Online (Sandbox Code Playgroud)

但由于某种原因,我只得到"mod.html"而不是forloop.counter号码.有谁知道发生了什么以及我可以做些什么来解决这个问题?非常感谢!

DTi*_*ing 46

你的问题是forloop.counter是一个整数,你使用add模板过滤器,如果你传递所有字符串或所有整数,但不是混合,它将表现正常.

解决这个问题的一种方法是:

{% for x in some_list %}
    {% with y=forloop.counter|stringformat:"s" %}
    {% with template="mod"|add:y|add:".html" %}
        <p>{{ template }}</p>
    {% endwith %}
    {% endwith %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

这导致:

<p>mod1.html</p>
<p>mod2.html</p>
<p>mod3.html</p>
<p>mod4.html</p>
<p>mod5.html</p>
<p>mod6.html</p>
...
Run Code Online (Sandbox Code Playgroud)

带有标记的第二个是必需的,因为stringformat标记是使用自动前置实现的%.要解决此问题,您可以创建自定义过滤器.我使用类似的东西:

http://djangosnippets.org/snippets/393/

将snipped保存为some_app/templatetags/some_name.py

from django import template

register = template.Library()

def format(value, arg):
    """
    Alters default filter "stringformat" to not add the % at the front,
    so the variable can be placed anywhere in the string.
    """
    try:
        if value:
            return (unicode(arg)) % value
        else:
            return u''
    except (ValueError, TypeError):
        return u''
register.filter('format', format)
Run Code Online (Sandbox Code Playgroud)

在模板中:

{% load some_name.py %}

{% for x in some_list %}
    {% with template=forloop.counter|format:"mod%s.html" %}
        <p>{{ template }}</p>
    {% endwith %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)