Antlers Conditional Parameters Using void Parameters

2 min read

In this article we are going to take a look at a way to conditionally supply a parameter to an Antlers tag using a new feature called void parameters. Void parameters allow you to conditionally remove a parameter completely, instead of simply passing null or false (which may have special meaning to some tags).

In the following example, we are using a standard if/else block to change the parameters that are being sent to the Collection tag. This works fine if the template is relatively small, but can get unwieldy as the size of the template inside the Collection tag pair grows:

1---
2show_all: false
3---
4 
5<ul>
6 {{ if view:show_all }}
7 {{ collection:articles sort="date:asc|title:desc" }}
8 <li>{{ title }}</li>
9 {{ /collection:articles }}
10 {{ else }}
11 {{ collection:articles sort="date:asc|title:desc" limit="3" }}
12 <li>{{ title }}</li>
13 {{ /collection:articles }}
14 {{ /if }}
15</ul>

Additionally, the sort="date:asc|title:desc" remains the same between both versions, and it can be easy to miss one if those values ever need to be updated. Antlers Runtime supports the concept of void parameters and the previous template could be rewritten to the following to produce the exact same result:

1---
2show_all: false
3---
4 
5<ul>
6 {{ collection:articles sort="date:asc|title:desc"
7 limit="{view:show_all ? void : 3}" }}
8 <ul>{{ title }}</ul>
9 {{ /collection:articles }}
10</ul>

In the latter version, we've replaced our large if/else block with a ternary expression. If view:show_all equals true the ternary expression returns the void keyword, otherwise it returns the value 3. When the Runtime engine encounters the void keyword, it will remove the parameter from the tag pair as if it was never supplied in the first place!

Thanks for taking the time to read this post! If you found this article useful and want to help support more work like this, please consider sponsoring my work on GitHub, or by checking out some merch.

 Sponsor on GitHub  Shop Merch