如何将 forloop.counter 连接到 django 模板中的字符串 [英] How can I concatenate forloop.counter to a string in my django template

查看:29
本文介绍了如何将 forloop.counter 连接到 django 模板中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在尝试像这样连接:

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 %}    

但由于某种原因,我只得到mod.html"而不是 forloop.counter 编号.有谁知道发生了什么以及我可以做些什么来解决这个问题?非常感谢!

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!

推荐答案

您的问题是 forloop.counter 是一个整数,并且您正在使用 add 模板过滤器,如果您通过,它将正常运行它是所有字符串或所有整数,但不是混合.

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:

{% 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 标记是通过自动添加的 % 实现的.为了解决这个问题,您可以创建一个自定义过滤器.我使用类似的东西:

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/

将截图保存为 some_app/templatetags/some_name.py

save the snipped as 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 %}

这篇关于如何将 forloop.counter 连接到 django 模板中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆