Django:在temp中神秘的字符串填充

2024-06-02 05:34:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用以下模板代码来尝试生成格式为“a、b、c和d”的列表:

{% for item in list %}
  {% if not forloop.first %}
    {% if not forloop.last %}
      ,
    {% endif %}
  {% endif %}
  {% if forloop.last %}
    and
  {% endif %}
  {{ item }}
{% endfor %}

我得到的实际输出是'a,b,c和d'(注意逗号前面的空格)。在

怎么回事?我怎么解决?在


Tags: and代码in模板列表forif格式
3条回答

好吧,经过几次尝试,我想我找到了一个解决方案,它有点冗长,但它能满足您的需要-没有多余的空间-

{% for item in list %}
    {% if forloop.revcounter > 2 %}
        {{ item }},
    {% else %}
         {% if forloop.revcounter == 2 %}
              {{ item }} and
         {% else %}
              {{ item }}
         {% endif %}
    {% endif %}
{% endfor %}

forloop.revcounter正在从循环的末尾开始倒数,因此您将“and”添加到最后一个项中,并将最后一个项保留为空。在

Django插入模板包含的所有空格:

{% for item in list %}{% if not forloop.first %}{% if not forloop.last %}, {% endif %}{% endif %}{% if forloop.last %} and {% endif %}{{ item }}{% endfor %}

顺便说一下,如果列表只包含一个值,那么模板将呈现错误的输出。更正的模板如下所示:

^{pr2}$

如果没有多余的空间,它就会变成:

{% for item in list %}{% if not forloop.first %}{% if forloop.last %} and {% else %}, {% endif %}{% endif %}{{ item }}{% endfor %}

我要做一个简单的template filter

@register.filter
def format_list(li):
    """
    Return the list as a string in human readable format.

    >>> format_list([''])
    ''
    >>> format_list(['a'])
    'a'
    >>> format_list(['a', 'b'])
    'a and b'
    >>> format_list(['a', 'b', 'c'])
    'a, b and c'
    >>> format_list(['a', 'b', 'c', 'd'])
    'a, b, c and d'
    """
    if not li:
        return ''
    elif len(li) == 1:
        return li[0]
    return '%s and %s' % (', '.join(li[:-1]), li[-1])

我还不是python方面的专家,可能还有更好的方法。但是,这在“django级别”上似乎很干净,就这样使用它:

^{pr2}$

我喜欢这个解决方案的原因是它是可重用的,可读性更强,代码更少,并且有测试。在

有关如何安装的详细信息,请参阅writing template filters上的文档。在

另外,您可能会注意到这个函数带有doctest,请参考django documentation来了解如何运行测试。在

有个办法:

>>> python -m doctest form.py -v
Trying:
    format_list([''])
Expecting:
    ''
ok
Trying:
    format_list(['a'])
Expecting:
    'a'
ok
Trying:
    format_list(['a', 'b'])
Expecting:
    'a and b'
ok
Trying:
    format_list(['a', 'b', 'c'])
Expecting:
    'a, b and c'
ok
Trying:
    format_list(['a', 'b', 'c', 'd'])
Expecting:
    'a, b, c and d'
ok
1 items had no tests:
    form
1 items passed all tests:
   5 tests in form.format_list
5 tests in 2 items.
5 passed and 0 failed.
Test passed.

相关问题 更多 >