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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With