Challenge #13 – Get your Ducks in a Row

11 September 2023 Open Twig Intermediate

You’ve built a beau­ti­ful set of product fil­ters that, when selec­ted, nar­row the res­ults of avail­able products in an online store. You’ve also figured out how to append the fil­ter val­ues to the URL so that links can be saved and shared. But at the final hour, the mar­ket­ing depart­ment” swoops in and presents a non-nego­ti­able”:

Fil­ter val­ues must appear in the URL in a spe­cif­ic order, for example:

garmentsforducks.com/products?cut=slim&colour=green&size=m&style=casual

Rather than ask why (you learned your les­son last time you chal­lenged an unusu­al request of theirs), you decide to get right to it so that no ducks get left out in the cold.

The fil­ters are saved as entries in a struc­ture sec­tion called Filters. The fil­ter val­ues are stored in an asso­ci­at­ive 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.

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 Git­Hub repo con­tains a Craft CMS site that you can spin up with a single com­mand, either loc­ally or in the browser using a Git­Hub codespace (see the readme file in the repo). The index.twig tem­plate con­tains sample inputs and out­puts that you can use to test your solu­tion as you work on it.

Sample inputs and outputs

Rules

Your solu­tion should con­sist of the Twig logic that first fetches the fil­ters entries and then manip­u­lates the filtersValues vari­able to pro­duced the expec­ted out­put. It should work with any input using the format shown. No plu­gins or mod­ules may be used.

Tips

This chal­lenge can be solved using Twig fil­ters or some less­er-known Col­lec­tion meth­ods in a rather eleg­ant way (without requir­ing any for loops). The key” lies in how you query the fil­ter entries.

Acknow­ledge­ments

  • Writ­ten by Ben Croker 
  • Dock­er setup by Andrew Welch (Spin Up Craft)

Solution

Submissions will be closed on 15 October 2023.

Submit A Solution