我已经尝试像这样连接:
{% 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编号。有人知道这是怎么回事吗?我能做些什么来解决这个问题?非常感谢!
发布于 2011-04-20 14:22:23
您的问题是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标签是用一个自动预置的%
实现的。要解决此问题,可以创建自定义筛选器。我使用类似这样的东西:
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 %}
发布于 2011-04-20 15:23:01
您可能不想在模板中这样做,这看起来更像是一个视图作业:(在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()
可能就是你要找的东西。
https://stackoverflow.com/questions/5725794
复制相似问题