Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I insert HTML at repeating intervals in expressionengine?

I have a loop of entries and I want to apply formatting to every second entry - not just applying a class but also some basic HTML markup. How can I do this?

like image 283
Jean St-Amand Avatar asked Oct 24 '12 13:10

Jean St-Amand


2 Answers

This question seems to come up a lot so I thought I would post a simple example:

{exp:channel:entries channel="whatever"}
{switch="<div class='entry'>|"}
<h2>{title}</h2>
{if count != total_results}{switch="|</div>"}{/if}
{if count == total_results}</div>{/if}
{/exp:channel:entries}

In this example, a div with a class of "entry" is wrapped around every second entry. The switch variable at the front end is pretty straight forward. The back end uses two conditionals: if the entry is the last entry in the loop, close the DIV. If the entry is NOT the last entry in the loop, close the DIV only for every second entry (a reflection of the switch variable at the beginning of the loop).

Important to note here that the switch variable is very sensitive to quotes - so when inserting HTML in this fashion, inside the switch variable, you have to use single quotes rather than double quotes. This is fine for simple insertions, but may be a bit unfriendly if you have more complex formatting in mind. Hopefully this helps some folks and feel free to expand on this idea.

like image 136
Jean St-Amand Avatar answered Oct 04 '22 23:10

Jean St-Amand


There is also a plugin which might help in this situation GWcode Alternate. I haven't used it myself as I prefer to use the native switch tag mentioned in the other answer.

like image 24
CreateSean Avatar answered Oct 04 '22 23:10

CreateSean