【问题标题】:separate items with comma in template在模板中用逗号分隔项目
【发布时间】:2013-07-16 11:55:15
【问题描述】:

模板.html

{% if leftbar.where_tab.0.location.title or leftbar.report.other_location or leftbar.report.location_description%}
{%with leftbar.where_tab.0.location.title|add:leftbar.report.other_location|add:leftbar.report.location_description as pi%}
{% if pi|length > 36 %}{{pi|slice:"36"}}...{% else  %}{{pi}}{% endif %}
{% endwith %}{%else%}Where{%endif%}

我想在每个项目之间添加一个逗号(,)。现在它显示时没有任何逗号,它全部显示在一行中。项目之间需要一个分隔符,而不是最后。

【问题讨论】:

  • 我在这里看不到循环。多个项目来自哪里?
  • if 不是循环。这是一个条件检查。要实现您正在寻找的内容,您需要一个模板标签。如果您尝试通过模板进行操作,它可能会变得非常混乱。

标签: django django-models django-templates


【解决方案1】:

你可以写一个模板标签来实现你想要的:

{% load_pi %}
{% display_pi leftbar %} 

在模板标签pi.py

from django import template

register = template.Library()

def display_pi(leftbar):

    title = leftbar.get('where_tab')[0].location.title if leftbar.get('where_tab') and leftbar.get('where_tab')[0].location else ''
    location = leftbar.report.other_location if leftbar.get('report') else ''
    description = leftbar.report.location_description if leftbar.get('report') else ''

    if any([title, location, description]):
        avail = ", ".join([x for x in [title, location, description] if x])
        return (avail[:36] + '..') if len(avail) > 36 else avail
    return "Where"

register.simple_tag(display_pi)

请更严格地检查错误。

【讨论】:

  • 我在模板中收到此错误“Caught AttributeError while rendering: 'dict' object has no attribute 'where_tab'”在模板中我使用这一行来加载模板标签,因为我已经在使用它了。{% load templatetags %}
  • 然后适当修改模板标签。
  • 我强烈建议您学习根据错误消息进行调试。它清楚地表明dict 没有属性where_tab' . which means, leftbar.where_tab` 应该是leftbar.get('where_tab')
猜你喜欢
  • 2012-01-14
  • 1970-01-01
  • 2021-12-29
  • 2010-11-17
  • 2021-12-31
  • 2014-08-01
  • 1970-01-01
  • 2012-02-17
  • 2021-02-09
相关资源
最近更新 更多