【问题标题】:How to sort the output of this django template code in alphabetical order?如何按字母顺序对这个 django 模板代码的输出进行排序?
【发布时间】:2011-05-31 16:16:57
【问题描述】:

我在 django 模板中有以下代码:

{% for object in object_list %}
{% with game=object.game %}

<a href="{% url game_view game.id game.title|slugify %}" class="img_link alphabeticList">{{game.title}}</a>

{% endwith %}
{% endfor %}

输出当前类别下的所有游戏,例如:

Armor Dude
Midnight Strike
Super Mafia Bros
Mission To Mars
Zed
game1 test 3
Examine the mystery of the crime in Apartment 13
Manor Freedom : The Patron's Chamber
Escape Journey
Outrun Summer Camp
Make your way through zombies hordes
Intelligent Guy
Run 3D : The Bathroom
Lady Gaga Escape Game
Insane Box
Will you do me A Small Favor?
Shanty Breakout
Cloudy Tumble Second Chaptert
Hotel Area Lock In
Escape From the Aircraft Hangar
RANDOM GAMES
Scene of the Caper: Gold Toy Scene of the Caper: ...    
Escape Journey Escape Journey
Cloudy Tumble Second Chaptert Cloudy Tumble Second...   
Midnight Strike Midnight Strike
BB EXCLUSIVES
Soldier Of Pain Soldier Of Pain     
Walk The Stork Walk The Stork

我怎样才能让输出按字母顺序和每个游戏标题开头的字母排序,例如:

A
---

Apple
Alligator

B
---

Burger
Bungee
Bear

C
---

cat

等等……

请注意,我只能使用模板标签,无法访问任何 python 代码。

【问题讨论】:

  • 我猜你不允许编写自定义标签?
  • @digitaldreame 不,我是前端开发人员
  • 那么使用 Javascript 对它们重新排序怎么样?

标签: python django


【解决方案1】:

我讨厌在模板中加入太多逻辑。通常,我要么将列表分组在视图中,要么有一个自定义标签来为我处理处理。我真的不知道这样的事情是否可行,但也许切片、分离和重新组合的某种组合可以得到你需要的东西?

如果不是,那么 JavaScript 可能是您唯一的方法;虽然这当然不推荐。

{% regroup object_list|dictsort:"game.title" by game.title|upper|slice:"0" as grouped_list %}

{% for group in grouped_list %}
  <p>{{ group.grouper }}</p>

  {% for game in group.list %}
  <a href="{% url game_view game.id game.title|slugify %}" class="img_link alphabeticList">{{ game.title }}</a>
  {% endfor %}
{% endfor %}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-22
    • 1970-01-01
    • 2013-04-03
    • 1970-01-01
    • 1970-01-01
    • 2014-02-26
    • 1970-01-01
    • 2011-08-29
    相关资源
    最近更新 更多