Dynamic Class Names with ExpressionEngine

Posted on 7 March 2011 | by Ryan Battles

When adapting a template into ExpressionEngine, it is a common occurrence to see items such as class=“first” and class=“last” when looking at a list of items. What follows is a simple explanation of some of the ExpressionEngine conditionals that you can use to work through these situations.

Situations such as these are no problem when we are using static code to run our pages.  However, we use ExpressionEngine, and we have the power of flexibility.  Also, clients often add, remove, and rearrange entries that might be used to make up lists like this, so we need to develop code that can handle that flexibility.

For example, your sidebar navigation might look something like this:

<ul id="side_nav">
    <
li class="first"><a href="#">Item 1</a></li>
    <
li><a href="#">Item 2</a></li>
    <
li><a href="#">Item 3</a></li>
    <
li><a href="#">Item 4</a></li>
    <
li class="last"><a href="#">Item 5</a></li>
</
ul

If your list is based off of a dynamic loop of entries, and is therefore out of your control once your client begins entering content, you can use ExpressionEngine’s conditional statements with the variables for “count” and “total_results” as follows:

<ul id="side_nav">
    
{exp:channel:entries channel="about_pages"}
    
<li 
        {if count
=="1"class="first" {/if}
        {if 
"{count}"=="{total_results}"class="last" {/if}
    
>
    <
a href="#">{title}</a></li>
    
{/exp:channel:entries}
</ul

A somewhat related pattern is to use the “switch” feature of ExpressionEngine loops, which can be used to throw in class names at set intervals.  For example, you can easily stripe tables by converting this code:

<table>
<
tr class="even">...</tr>
<
tr class="odd">...</tr>
<
tr class="even">...</tr>
<
tr class="odd">...</tr>
</
table

To this:

<table>
    
{exp:channel:entries channel="table_rows"}
    
<tr class="{switch="even|odd"}">...</tr>
    
{/exp:channel:entries}
</table

If you want to use the switch statement and only apply a value to every 3rd entry, you would use something like this:

class="{switch="||third_entry"}" 

It is fine to leave no values between the pipe characters, the switch will then be skipped over.

I know that this stuff can be found in the ExpressionEngine docs, but sometimes, for one strange reason or another, people don’t read through every page and miss stuff like this!

Tags: expressionengine, template

Related Posts

Comments (3)

Sajid Iqbal
Nov. 19, 2011

thanks, you solved my problem

electronic cigarettee,cigarette uk
Jan. 28, 2012

Thanks it is a great engine.

Loughlin
Apr. 29, 2012

Thank you, was trying to figure this out!

Commenting is no longer available for this entry.