如何将 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 数字。有谁知道发生了什么事以及我可以采取什么措施来解决这个问题?多谢!
I am already trying to concatenate like this:
{% for choice in choice_dict %}
{% if choice =='2' %}
{% with "mod"|add:forloop.counter|add:".html" as template %}
{% include template %}
{% endwith %}
{% endif %}
{% endfor %}
but for some reason I am only getting "mod.html" and not the forloop.counter number. Does anyone have any idea what is going on and what I can do to fix this issue? Thanks alot!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的问题是 forloop.counter 是一个整数,并且您正在使用
add
模板过滤器,如果您向其传递所有字符串或所有整数(但不是混合),该过滤器将正常运行。解决此问题的一种方法是:
其结果是:
需要第二个 with 标记,因为 stringformat 标记是使用自动前置的
%
实现的。为了解决这个问题,您可以创建一个自定义过滤器。我使用类似的东西:http://djangosnippets.org/snippets/393/
保存截图 some_app/templatetags/some_name.py :
作为模板中的
Your problem is that the forloop.counter is an integer and you are using the
add
template filter which will behave properly if you pass it all strings or all integers, but not a mix.One way to work around this is:
which results in:
The second with tag is required because stringformat tag is implemented with an automatically prepended
%
. To get around this you can create a custom filter. I use something similar to this:http://djangosnippets.org/snippets/393/
save the snipped as some_app/templatetags/some_name.py
in template:
您可能不想在模板中执行此操作,这看起来更像是视图作业:(在 for 循环中使用 if )。
然后将
chosen_templates
传递到您的模板,您将只拥有另外,我不太明白为什么您使用字典来选择具有不在字典中的数字的模板。
对于 dict.items() 中的 key,value
可能就是您正在寻找的内容。You probably don't want to do this in your templates, this seems more like a views job: (use of if within a for loop).
Then pass
chosen_templates
to your template where you will have onlyAlso, I don't quite understand why you are using a dict to select the template with a number that is not in the dictionnary.
for key,value in dict.items()
may be what you are looking for.尝试without使用“with”块
Try without using the block "with"