首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何将forloop.counter连接到django模板中的字符串

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

Stack Overflow用户
提问于 2011-04-20 13:12:40
回答 2查看 14.2K关注 0票数 20

我已经尝试像这样连接:

代码语言:javascript
复制
{% 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编号。有人知道这是怎么回事吗?我能做些什么来解决这个问题?非常感谢!

EN

回答 2

Stack Overflow用户

发布于 2011-04-20 14:22:23

您的问题是forloop.counter是一个整数,并且您使用的是add模板过滤器,如果您传递给它的是全部字符串或全部整数,而不是混合传递,则该过滤器将正常工作。

解决此问题的一种方法是:

代码语言:javascript
复制
{% for x in some_list %}
    {% with y=forloop.counter|stringformat:"s" %}
    {% with template="mod"|add:y|add:".html" %}
        <p>{{ template }}</p>
    {% endwith %}
    {% endwith %}
{% endfor %}

这会导致:

代码语言:javascript
复制
<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

代码语言:javascript
复制
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)

在模板中:

代码语言:javascript
复制
{% load some_name.py %}

{% for x in some_list %}
    {% with template=forloop.counter|format:"mod%s.html" %}
        <p>{{ template }}</p>
    {% endwith %}
{% endfor %}
票数 48
EN

Stack Overflow用户

发布于 2011-04-20 15:23:01

您可能不想在模板中这样做,这看起来更像是一个视图作业:(在for循环中使用if )。

代码语言:javascript
复制
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传递给您的模板,在该模板中您将只拥有

代码语言:javascript
复制
{% for template in chosen_templates %}
  {% load template %}
{% endfor %}

另外,我也不太明白为什么你要用字典来选择一个字典里没有的数字模板。for key,value in dict.items()可能就是你要找的东西。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5725794

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档