Search code examples
switch-statementexpressionengine

Alternating row colors in ExpressionEngine table


I have some code that creates a table that alternates row colors based on the row value of the entry.

<table class="authorList" cellspacing="0">
{exp:channel:entries channel="team" disable="categories|member_data|pagination" orderby="team-last-name" sort="asc"}
{if team-not-with-us != 'y'}
    <tr class="{switch="odd|even"} authorInfo">

      <th class="authorName">
        {if team-bio != ''}<a href="{site_url}about/the-team/{url_title}">{/if}
          {title}
        {if team-bio != ''}</a>{/if}
      </th>
      <td class="position">{team-position}</td>

    </tr>
{/if}
{/exp:channel:entries}
</table>

The problem is when I delete an entry, I end up having two odd or two even numbers in a row, leaving me with two like-colored rows side by side.

While the switch function is convenient, it is referencing the row count within the database. I don't believe I can apply it to reference the actual row count in the if statement which would solve my problem. (Correct me if I'm wrong.)

I know how to make this change with php:

<?php $oddevenrow = 0; ?>
{if team-not-with-us != 'y'}
    <?php $oddevenrow++; ?>
    <?php ($oddeven = ($oddevenrow % 2 ? 'odd' : 'even')); ?>
    <tr class="<?php echo $oddeven; ?> authorInfo">

But I'm not allowed to turn PHP on in the EE install.

Is there something similar I can do in EE?

Thanks!


Solution

  • You're looking for the switch tag.

    {switch="odd|even"}

    But it looks like you already knew that. It looks like you're requiring the variable team-not-with-us to != 'y'. Because you're doing that validation after results have been returned you'll end of with multiple odd or even rows next to each other. The easy way to avoid this is to use the channel:entries search param. Example: search:team-not-with-us="not y"

    <table class="authorList" cellspacing="0">
    {exp:channel:entries 
        channel="team" 
        disable="categories|member_data|pagination" 
        orderby="team-last-name" 
        sort="asc"
        search:team-not-with-us="not y"
    }
        <tr class="{switch="odd|even"} authorInfo">
    
          <th class="authorName">
            {if team-bio != ''}<a href="{site_url}about/the-team/{url_title}">{/if}
              {title}
            {if team-bio != ''}</a>{/if}
          </th>
          <td class="position">{team-position}</td>
    
        </tr>
    {/exp:channel:entries}
    </table>