A perch:if diet

Perch’s conditional tags is a powerful feature of its templating engine. Yet, you can in some cases replicate the outcome of perch:if tags with tag attributes and write less code in the process.

if, else

Instead of writing a perch:if and perch:else for simple content, you can use the else attribute. So this:

<perch:if exists="name"><perch:content id="name" type="text"><perch:else>Anonymous</perch:if>

becomes this:

<perch:content id="name" type="text" else="Anonymous">

Appending text

Sometimes you want to add some simple text if a field exists. For instance, when formatting an address you often append a comma after each segment. You can use the append attribute here. So this:

<perch:content id="city" type="text"><perch:if exists="city">,</perch:if>

becomes this:

<perch:content id="city" type="text" append=",">

Output text based on a value

It is common to add a checkbox field to give the editor the ability to enable/disable/apply an option.

<perch:content id="option" type="checkbox" label="Some Option" value="1" suppress>

<perch:if exists="option"><!--* do something *--></perch:if>

For example, you can add additional classes to elements:

class="some-class <perch:if exists="option">option-class</perch:if>"

A checkbox field potential value never changes. It either is that value or it is unchecked. That’s why you can use the replace tag here, so the above becomes this:

class="some-class <perch:content id="option" replace="1|option-class">"

I realise you can have the value of the checkbox field to be the class you want to output to begin with:

<perch:content id="option" type="checkbox" label="Some Option" value="option-class" suppress>
class="some-class <perch:content id="option">"

However, I don’t like doing that in many cases. If I need to change the class on an existing website, I can’t simply change the value attribute on the field. The value stored in the database is whatever the value was when you saved the edit form last. The alternative in that case would be to use conditional tags (or the replace attribute approach). So you might as well adapt this practice from the start.

The second this I am aware of here is that this apprach doesn’t yield less code:

<perch:if exists="option">option-class</perch:if>
<perch:content id="option" replace="1|option-class">

So why use this? I personally may use this in more complex templates that already has a lot of conditional tags if I find it helps the readability of the code.


Related articles