你的问题在于for循环计数器是一个整数,而你正在使用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>
...
需要使用带有标签的第二个字符串,因为stringformat标签是通过自动添加%
来实现的。 要解决此问题,您可以创建自定义过滤器。 我使用类似于以下内容的代码:
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 %}