getgrav / grav-plugin-taxonomylist

Grav TaxonomyList Plugin

Home Page:https://getgrav.org

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Sort Alphabetically

K232 opened this issue · comments

commented

Would it be possible to add a 'sort alphabetically' option? I had a look at taxonomy.html.twig but the For-loop has no 'order' clause or something similar. Any idea?

Sorry i lost track of this. This is easy enough to accomplish by overriding the partials/taxonomylist.html.twig file and have something like this:

{% set taxlist = taxonomylist.get() %}

{% if taxlist %}
<span class="tags">
    {% for tax,value in taxlist[taxonomy]|ksort %}
        <a href="{{ base_url }}/{{ taxonomy }}{{ config.system.param_sep }}{{ tax|e('url') }}">{{ tax }}</a>
    {% endfor %}
</span>
{% endif %}

Notice the |ksort filter that is sorting by key (ie, the name of the taxonomy type)

commented

Hi!
Is ksort deprecated after introducing sort_by_key? I tried both, but had no success so far. Would be great if you could help out :)

{% set taxlist = taxonomylist.get() %}
{% if taxlist %}
  {% set category = grav.uri.params("category", true) %}
  {% for tax,value in taxlist['category']|sort_by_key('tax') %}
    {% set current_page = (tax == category) ? 'active' : '' %}
    <li class="">
      <a href="{{ page.url }}/category{{ config.system.param_sep }}{{ tax|e('url') }}">{{ tax|capitalize }}</a>
    </li>
  {% endfor %}
{% endif %}

This issue is a bit old, but for anyone coming here adding |ksort works perfectly to sort your list alphabetically.

Confirm that ksort works fine.

commented

ksort works, but it's case-sensitive. So it sorts this way

  1. Category
  2. Example
  3. foo
  4. list

That's why I was first thinking it didn't work. Maybe it helps someone in the feature.

Working example of an category list with active class:

{% set taxlist = children_only is defined ? taxonomylist.getChildPagesTags() : taxonomylist.get() %}

{% set active = uri.param(taxonomy) is defined ? uri.param(taxonomy) : 'all' %}

{% set has_active = active != 'all' %}

{% if taxlist %}
    <li>
        {% set all_active = not uri.param(taxonomy) %}
        <a class="{{ all_active or (active == 'all' and not has_active) ? 'active' : '' }}" href="{{ base_url }}">Alle</a>
    </li>
    {% for tax, value in taxlist[taxonomy]|ksort %}
        {% if active == tax %}
            {% set has_active = true %}
        {% endif %}
        <li>
            <a class="{{ active == tax ? 'active' : '' }}" href="{{ base_url }}/{{ taxonomy }}{{ config.system.param_sep }}{{ tax }}">{{ tax }}</a>
        </li>
    {% endfor %}
{% endif %}