Python 如何将forloop.counter连接到django模板中的字符串
我已经在尝试这样连接:Python 如何将forloop.counter连接到django模板中的字符串,python,django,django-templates,for-loop,string-concatenation,Python,Django,Django Templates,For Loop,String Concatenation,我已经在尝试这样连接: {% for choice in choice_dict %} {% if choice =='2' %} {% with "mod"|add:forloop.counter|add:".html" as template %} {% include template %} {% endwith %} {% endif %} {% endfor %} 但
{% 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 %}
在模板中:
{% load some_name.py %}
{% for x in some_list %}
{% with template=forloop.counter|format:"mod%s.html" %}
<p>{{ template }}</p>
{% endwith %}
{% endfor %}
{%loadesome\u name.py%}
{%x在某些_列表%}
{%with template=forloop.counter |格式:“mod%s.html”%}
{{template}}
{%endwith%}
{%endfor%}
您可能不想在模板中执行此操作,这更像是一个视图作业:(在for循环中使用if)
然后将所选的\u模板传递给您的模板,您只需要
{% for template in chosen_templates %}
{% load template %}
{% endfor %}
另外,我也不太明白为什么你要用dict来选择一个没有在字典里的数字的模板对于键,dict.items()中的值可能就是您要查找的内容。尝试不使用“with”块
计数器是一个int而不是字符串,我认为这是导致problem@Ethan:这似乎回答了您的问题,不是吗?@dting-这非常有效,除非您使用forloop.counter0
调用它,在这种情况下,if value
行将为“0”返回“False”。要解决这个问题,只需将该行更改为,如果值不是None
。值得注意的是,您需要在templatetags目录中使用init.py,并重新启动服务器,以便按照:NIce注册,不幸的是,这不适用于Django 1.9。
{% load some_name.py %}
{% for x in some_list %}
{% with template=forloop.counter|format:"mod%s.html" %}
<p>{{ template }}</p>
{% endwith %}
{% endfor %}
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)
{% for template in chosen_templates %}
{% load template %}
{% endfor %}
{% for choice in choice_dict %}
{% if choice =='2' %}
{% include "mod"|add:forloop.counter|add:".html" %}
{% endif %}
{% endfor %}