The else attribute and falsy values

The Perch templating engine has a number of ways that allows you to conditionally output content (and markup). One of these ways is the else attribute. It provides a quick and easy way to output a default if a field is empty:

<perch:content id="success_url" type="text" else="/thank-you">

However, the templating engine (as of v3.1.5) won’t output anything if you use some falsy values like false or 0:

<perch:content id="option" type="checkbox" value="true" else="false">

In this case you can use !true if you need to output something that evaluates to false (e.g. in Javascript):

<perch:content id="option" type="checkbox" value="true" else="!true">

Alternatively, you can use the perch:if conditional tags:

<perch:if exists="option">
    <perch:content id="option" type="checkbox" value="true">
<perch:else>
    false
</perch:if>

Example

A practical use case would be giving the editor the option to overwirte an Alpine.js component’s the defaults. Here is a sample dropdown component from Alpine.js’s docs:

<div x-data="{ open: false }">
    <button @click="open = true">Open Dropdown</button>

    <ul x-show="open" @click.away="open = false">
        Dropdown Body
    </ul>
</div>

The dropdown is closed by default, but if you wanted to the editor to overwrite this default, you can add a checkbox field to a Perch template:

<div x-data="{ open: <perch:content id="open" type="checkbox" value="true" else="!true"> }">
    <button @click="open = true">Open Dropdown</button>

    <ul x-show="open" @click.away="open = false">
        Dropdown Body
    </ul>
</div>
link

Related articles