使用 Twig 按字母顺序排序

Sort alphabetically with Twig

我正在尝试按字母顺序对类别列表进行排序。因为这更像是一个 PHP 缺陷,所以我正在尝试以描述 here 的方式来做到这一点。我真的无权访问系统的核心文件,因此需要使用 Twig 标签来完成。

在 Twig 数组中使用数字变量作为键时,无法使用内置的排序过滤器过滤器。这是一个非常具体的问题,是由于使用了 array_merge php 函数

我正在尝试将 link 中的代码合并到我自己的代码中,但无法正确完成。

我这样称呼我的类别:

{% for category in shop.categories %}
  {{ category.title }} - {{ category.id }}
{% endfor %}

如果我理解代码正确,我应该做如下事情:

{% set tempArray = {} %}

      {% for category in shop.categories %}
      numeric : {{ category.id }}, text : {{ category.title }} <br />
        {% set tempArray = tempArray | merge({('_' ~ category.numeric):(category.text)}) %}
      {% endfor %}

      {% for val in loopArray %}
      {{ tempArray['_' ~ val] }} <br/ >
      {% endfor %}

这不会对类别名称进行排序,但仍然会对类别 ID 进行排序。

有什么我遗漏的吗?

忘记你给的 link (http://obtao.com/blog/2014/06/use-variable-key-twig-array/),它只是一个不对数组排序的糟糕源代码。

但是看看那里: Sorting in the template, in Symfony2: using Twig to sort a collection of objects by property

如果不创建自己的过滤器,就无法根据 twig 中的类别名称对数组进行排序。您自己的过滤器将进行排序,您将能够在您的树枝模板中使用它。

====不读但是如果你想知道什么不好link ====

在这个糟糕的link中,这家伙通过手动设置他想要的顺序在行中排序

{% set loopValues =  [10,20,30,40] %}

其实他所有的post都是为了表明

{{ tempArray[val] }} doesn't work with val as a numeric

但适用于

 {{ tempArray['_'~val] }} 

在一个卑鄙的把戏之后(但它可能只适用于:{{ tempArray[''~val] }} 但是 link 给出的代码没用并不重要...