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

|| 我已经在尝试像这样串联:
{% for choice in choice_dict %}
    {% if choice ==\'2\' %}
        {% with \"mod\"|add:forloop.counter|add:\".html\" as template %}
            {% include template %}
        {% endwith %}                   
    {% endif %}
{% endfor %}    
但是由于某种原因,我只能得到\“ mod.html \”而不是forloop.counter编号。有谁知道发生了什么事以及我可以做什么来解决此问题?非常感谢!
已邀请:
您的问题是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 %}
结果是:
<p>mod1.html</p>
<p>mod2.html</p>
<p>mod3.html</p>
<p>mod4.html</p>
<p>mod5.html</p>
<p>mod6.html</p>
...
第二个with标记是必需的,因为stringformat标记是通过自动加前缀ѭ4来实现的。为了解决这个问题,您可以创建一个自定义过滤器。我使用类似的东西: http://djangosnippets.org/snippets/393/ 将片段保存为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)
在模板中:
{% load some_name.py %}

{% for x in some_list %}
    {% with template=forloop.counter|format:\"mod%s.html\" %}
        <p>{{ template }}</p>
    {% endwith %}
{% endfor %}
您可能不想在模板中执行此操作,这看起来更像是一个视图作业:(在for循环中使用if)。
chosen_templates=[]
for choice in choice_dict:
  if choice ==\'2\':
    {% with \"mod\"|add:forloop.counter|add:\".html\" as template %}
    template_name = \"mod%i.html\" %index
    chosen_templates.append(template_name)
然后将
chosen_templates
传递给您的模板
{% for template in chosen_templates %}
  {% load template %}
{% endfor %}
另外,我不太明白为什么您要使用字典来选择模板,而该模板中的数字不在字典中。
for key,value in dict.items()
可能是您想要的。
尝试不使用块“ with”
{% for choice in choice_dict %}
    {% if choice ==\'2\' %}
       {% include \"mod\"|add:forloop.counter|add:\".html\" %}                   
    {% endif %}
{% endfor %} 

要回复问题请先登录注册