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?
3 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.

- 793
- 5
- 12
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.

- 1,286
- 1
- 21
- 42
The example I had used was specifically for those instances in which a DIV is not desired on EVERY entry but rather a wrapping DIV around certain intervals - common when you want to have a jQuery slider that includes 3 entries at a time, for example. This was expressly the purpose of my example. EVERY entry is not what I would consider intervals, which is what my example was intended for. Certainly it is an edge case - but an edge case that occurs often enough to capture a simple solution to the challenge that still uses native functionality with only simple conditionals.

- 793
- 5
- 12
-
Apologies, I misinterpreted the post and have deleted my response. For what it's worth [Columnbo](http://devot-ee.com/add-ons/column-bo) is a tool worth looking at for this sort of thing. It's a little neater than using the `{switch}` tag and scales better if you want an interval of say, every 10 items. – Dom Stubbs Oct 29 '12 at 11:50
-
No worries - I was just looking to post something purely native. Certainly there are some add-ons that can allow you to do something similar without the conditionals. – Jean St-Amand Oct 30 '12 at 16:59