Radical Design Course by Jack McDade

From the creator of Statamic

Learn how to make your websites standout and be remembered.

Bought Jack McDade's course on design. Going through it now...and it is SO well done!

— Justin Jackson, Transistor.fm

Switch Tag

Each time a switch tag is rendered it will return the next value from its between parameter until it reaches the end where it will start all over again.

Overview

The switch tag is most often used to write HTML classes in your markup to help style lists and grids of items. While CSS has gained a lot of features in recent years with CSS selectors like nth-of-type, the switch tag is more relevant than ever, especially in combination with utility frameworks like TailwindCSS.

Examples

Here are a few ideas on what you can do with the switch tag.

Set alternating background color for table rows

<table>
{{ collection:shows }}
<tr class="{{ switch between='bg-white|bg-grey-100' }}">
<th>{{ title }}</th>
<td>{{ rating }}</td>
<tr>
{{ /collection:shows }}
</table>

Reverse every other pair of items with flex-direction: row-reverse

{{ features }}
<div class="flex {{ switch between='flex-row|flex-row-reverse' }}">
<div class="w-1/2 px-4 m-2">
<h2>{{ feature_name }}</h2>
<div>{{ description }}</div>
</div>
<img src="{{ feature_screenshot }}" class="w-1/2 m-2">
</div>
{{ /features }}

Multiple Instances

You can have multiple instances of the switch tag in a single view and they won't collide with each other as long as the your set of parameters is unique.

If you want to have multiple, identical switch tags you can add an extra parameter to keep track of which is which.

{{ switch between="even|odd" for="gallery" }}
{{ switch between="even|odd" for="footer" }}

Repeating Values

If you have a lot of redundancy in your between parameter, you can simplify it by passing in the number of times you want an element to be repeated.

For example, if you'd like to set the background of every 10th element to purple, you could set the first value to white 9 times followed by purple 1 time.

{{ switch between="bg-white:9|bg-purple" }}
Hot Tip!

If you're using TailwindCSS's JIT mode or you purge your CSS on production, you might notice any classes only in your switch tag are missing. Add spaces around the pipes to make sure JIT picks them up.

{{ switch between="bg-white | bg-purple" }}

Parameters

between

array

A set of values to iterate over, using a pipe-separated string.

Docs feedback

Submit improvements, related content, or suggestions through Github.

Betterify this page →