Search code examples
switch-statementexpressionengine

ExpressionEngine swtich tag working inconsistently


In ExpressioneEngine, I'm creating a list with conditionals that is returning some strange behavior. The code below is part of a bigger set:

<li><h4>DERMATOLOGY</h4>
  <ul>
    {exp:channel:entries channel="specialist" dynamic="no" orderby="sp_order" sort="asc"}
      {if sp_specialty == "sp_dermatology"}
        <li>
          <a href="{title_permalink='meet'}"><img src="{sp_headshot}" /></a>
          <a href="{title_permalink='meet'}"><p>{title}</p></a>
        </li>                           
      {/if}
    {/exp:channel:entries}
  </ul>
</li>
<li><h4>EMERGENCY AND CRITICAL CARE</h4>
  <ul>
    {exp:channel:entries channel="specialist" dynamic="no" orderby="sp_order" sort="asc"}
      {if sp_specialty == "sp_emergency"}
        <li class="{switch='one|two'}">
          <a href="{title_permalink='meet'}"><img src="{sp_headshot}" /></a>
          <a href="{title_permalink='meet'}"><p>{title}</p></a>
        </li>                           
      {/if}
    {/exp:channel:entries}
  </ul>
</li>

What happens, in the case of EMERGENCY AND CRITICAL CARE, is that with the 5 entries I have under that, the classes are returned like this: two, one, one, one, two. Any suggestions on getting the behavior I need?


Solution

  • I see what you mean. The switch variable applies its logic to all entries returned by the entries loop - which is why you're seeing odd numbering in your rendered page - because it's applying them to entries returned by the loop that you are then applying conditionals to in order to do your grouping. You could use the search param to do some of that for you, returning only the entries you're looking for within each loop. Like this:

    <li><h4>DERMATOLOGY</h4>
        <ul>
        {exp:channel:entries channel="specialist" search:sp_specialty="=sp_dermatology"  dynamic="no" orderby="sp_order" sort="asc"}
        <li>
          <a href="{title_permalink='meet'}"><img src="{sp_headshot}" /></a>
          <a href="{title_permalink='meet'}"><p>{title}</p></a>
        </li>                           
    {/exp:channel:entries}
    </ul>
    </li>
    <li><h4>EMERGENCY AND CRITICAL CARE</h4>
    <ul>
    {exp:channel:entries channel="specialist" search:sp_specialty="=sp_emergency" dynamic="no" orderby="sp_order" sort="asc"}
        <li class="{switch='one|two'}">
          <a href="{title_permalink='meet'}"><img src="{sp_headshot}" /></a>
          <a href="{title_permalink='meet'}"><p>{title}</p></a>
        </li>                           
    {/exp:channel:entries}
    </ul>
    </li>
    

    This way each loop returns ONLY the matching items you're looking for, eliminating the need for the conditional and allowing the switch param to operate as it wants to - applying itself in alternating fashion to every returned entry from the loop.