使用Django模板从dict列表创建上下文表

2024-09-30 05:22:52 发布

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

假设我有以下清单:

fruits = [
    {"Name": "Apple", "id": 1, "url": "/apple", "Desc": "Red or green skin with white flesh."},
    {"Name": "Pear", "id": 2, "url": "/pear", "Desc": "Green fruit with white flesh."},
    {"Name": "Coconut", "id": 3, "url": "/coco", "Desc": "Brown hairy shell with with flesh."}
]

它通过一个视图传递给Django模板的上下文。我该如何构建一个类似这样的上下文表呢?你知道吗


A
Apple
红色或绿色皮肤,肉白色。

C
Coconut
褐色有毛的壳,有肉。

P
Pear
果肉白的绿色水果。。

我在想这样做:

{% for fruit in fruits %}
    <B>{{ fruit.Name|first_letter_upper }}</B><BR>
    <A HREF="{{ fruit.url }}">{{ fruit.Name }}</A><BR>
    {{ fruit.Desc }}<BR>
    {% if not forloop.last %}<BR>{% endif %}
{% endfor %}

但接下来我必须实现自定义过滤器“first\u letter\u upper”。没什么大不了的,但我只是想知道是否有一种更简单的方法来做到这一点,而不必使用自定义过滤器?你知道吗


Tags: namebridurlapplewithdescfirst
2条回答

通过组合^{}^{}可以得到第一个大写字母。你知道吗

如果您只想在有多个项目(例如苹果和鳄梨)的情况下让字母出现一次,那么您可以使用^{}。你知道吗

{% for fruit in fruits %}
    {% ifchanged %}<B>{{ fruit.Name|slice:":1"|upper }}</B><BR>{% endifchanged %}
    <A HREF="{{ fruit.url }}">{{ fruit.Name }}</A><BR>
    {{ fruit.Desc }}<BR>
    {% if not forloop.last %}<BR>{% endif %}
{% endfor %}

您可以使用内置的^{}

{{ fruit.Name|capfirst }}

相关问题 更多 >

    热门问题