• photo + video

  • web + design

  • photography

Photography is our passion. Great design inspires us. Have a look around.

Willow Light Studio is a creative digital studio located in Westport Island, Maine. Our focus is on creating websites and producing content that best represent our clients. We believe that high quality media and a lightweight web design to showcase the content is the formula to a successful online presence, and beyond.

~ the latest ~

The Switch Conundrum: Closing tags with switch statements in ExpressionEngine

There are times when the {switch} functionality is used to open and close a <div> or a <li>. In such instances (and similar ones), if the switch statement is not reached due to an odd or even number of entries, the code is left without the closing tag.

This method described below could technically be used to entirely bypass using {switch} all together, but I prefer to keep the consistency of using it across all templates.

Here’s a scenario when you are creating a row and two columns in each row (using bootstrap classes):

{exp:channel:entries channel="news"}
{switch='<div class="row">|'}
<div class="col-lg-6 col-md-6 col-sm-12 col-xs-12">
{body}
</div>
{switch='|</div'}
{/exp:channel:entries}

In the example above, if you have 4 entries you’ll end up with two properly opened and closed <div> tags for rows. However, if you have 3 or any odd number, the last row will not have a closing tag.

Here’s a simple solution to the problem:

{exp:channel:entries channel="news"}
{switch='<div class="row">'}
<div class="col-lg-6 col-md-6 col-sm-12 col-xs-12">
{body}
</div>
{switch='|</div'}
{!-- If it is the last entry, check to see if it is an odd number --}
{if count == total_results}
{!-- If the remainder of total results divided by 2 is 1, then it is an odd number --}
{if total_results % 2 == 1}</div>{/if}
{/if}
{/exp:channel:entries}

The above code can easily be changed to check for an even number if the example above had 3 columns in each row.

View All News >