Search code examples
phpsortingsymfonytwig

Sort alphabetically with Twig


I'm trying to sort a list of categories in alphabetical order. Since this is more of a PHP flaw I'm trying to do this in a way which is described here. I really don't have access to the core files of the system so it need to be done with Twig tags.

The build in sort filter filters can't be used when using numeric variable as key in a Twig array. This is a very specific problem which is due to the use of the array_merge php function

I'm trying to incorporate the code in the link into my own code but I'm not able to get it done right.

I'm calling my categories like so:

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

If I understand the code correct I should do something like:

{% 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 %}

This doens't sort the category names but still the category id's.

Is there something I'm missing?


Solution

  • Forget the link you give (http://obtao.com/blog/2014/06/use-variable-key-twig-array/), it's simply a bad source code which doesn't sort an array.

    But have a look there : Sorting in the template, in Symfony2: using Twig to sort a collection of objects by property

    There is no way to sort your array on the category names in twig without create your own filter. Your own filter will do the sort and you will be able to use it in your twig templates.

    ==== do not read but if you want to know what do the bad link ====

    In this bad link the guy sort by manually set the order he wants in the line

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

    In fact all his post is to show that

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

    but works with

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

    after a dirty trick (but it would have probably work with just : {{ tempArray[''~val] }} but it's not important the code give by the link is useless...