python - 如何将 forloop.counter 连接到我的 django 模板中的字符串

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

但由于某种原因,我只得到“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 %}

导致:

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

关于python - 如何将 forloop.counter 连接到我的 django 模板中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5725794/

相关文章:

python - 二叉树的所有元素列表

python ascii 到 unicode 转换

python - 在 ADMIN_MENU_ORDER 中创建自定义项目

templates - 使用 Django 模板标签的 Jinja2 模板

python - itertools.groupby 中组大小的限制

python - python中的条件统计摘要数据框

python - 如何更改 django 注册电子邮件模板 "site"名称?

python - 在 django 中获取基于时间的模型统计信息

javascript - 删除模板中的 django url 前缀

django - 如何在模板中显示BooleanField名称?