You’ve built a beautiful set of product filters that, when selected, narrow the results of available products in an online store. You’ve also figured out how to append the filter values to the URL so that links can be saved and shared. But at the final hour, the “marketing department” swoops in and presents a “non-negotiable”:
Filter values must appear in the URL in a specific order, for example:
garmentsforducks.com/products?cut=slim&colour=green&size=m&style=casual
Rather than ask why (you learned your lesson last time you challenged an unusual request of theirs), you decide to get right to it so that no ducks get left out in the cold.
The filters are saved as entries in a structure section called Filters
. The filter values are stored in an associative array (a hash, as it’s called in Twig) called filterValues
. You need to ensure that they appear in the exact order as the entries in the Filters
section.
Here are some sample inputs and outputs.
{% set filters = { style: 'elegant', colour: 'green', size: 'm', cut: 'slim' } %}
{# Your solution code #}
{{ filters|url_encode }}
should output
cut=slim&colour=green&size=m&style=elegant
{% set filters = { size: 's', colour: 'yellow' } %}
{# Your solution code #}
{{ filters|url_encode }}
should output
colour=yellow&size=s
{% set filters = { cut: 'regular' } %}
{# Your solution code #}
{{ filters|url_encode }}
should output
cut=regular
This GitHub repo contains a Craft CMS site that you can spin up with a single command, either locally or in the browser using a GitHub codespace (see the readme file in the repo). The index.twig template contains sample inputs and outputs that you can use to test your solution as you work on it.
Your solution should consist of the Twig logic that first fetches the filters entries and then manipulates the filtersValues
variable to produced the expected output. It should work with any input using the format shown. No plugins or modules may be used.
This challenge can be solved using Twig filters or some lesser-known Collection methods in a rather elegant way (without requiring any for
loops). The “key” lies in how you query the filter entries.