We use cookies to improve your experience. No personal information is gathered and we don't serve ads. Cookies Policy.

ExpressionEngine Logo ExpressionEngine
Features Pricing Support Find A Developer
Partners Upgrades
Blog Add-Ons Learn
Docs Forums University
Log In or Sign Up
Log In Sign Up
ExpressionEngine Logo
Features Pro new Support Find A Developer
Partners Upgrades
Blog Add-Ons Learn
Docs Forums University Blog
  • Home
  • Forums

Plugin: Switchee

Development and Programming

Mark Croxton's avatar
Mark Croxton
319 posts
about 16 years ago
Mark Croxton's avatar Mark Croxton

A very simple plugin that allows you to create switch/case control logic in your templates.

With EEs if/else conditionals, each condition is parsed before being removed at the end of the parsing process. This means if you wrap if/else tags around lots of other tags then your template will be running many unnecessary queries and functions.

As Switchee is a tag we can use parse=”inward” to ensure that unmatched conditions are not parsed before being removed from the template.

Switchee can only be used for simple conditional logic. Like PHPs switch/case, it supports a default value.

Example:

{exp:switchee variable = "{variable_to_test}" parse="inward"}
    
    {case value="value1|value2"}
        Content to show
    {/case}
    
    {case value="value3" default="Yes"}
        Content to show
    {/case}
    
    {case value="#^P(\\d+)$#|''"}
        Use regular expressions enclosed by hashes #regex#
        Be careful to encode the following reserved characters as follows:
        { = & #123;
        | = & #124;
        } = & #125;
        Use '' to represent an empty string
    {/case}
    
{/exp:switchee}

Note that ‘default’ can also be used on it’s own:

{case default="Yes"}

In some of my templates I’ve seen a 30% decrease in queries by using Switchee in preference to if/else.

17 Feb 2010 - updated to version 1.1 * Now allows multiple case values separated by pipe ‘|’.

19 Feb 2010 - updated to version 1.2 * Now supports regular expression matching like so: #regex# * Supports empty string matches represesnted by ” or “”

22 Feb 2010 - updated to version 1.3 * Added support for reserved characters in regular expressions * Multiple regular expressions separated by | can now be used safely for one case value

24 Feb 2010 - updated to version 1.4 * fixed a minor bug

Still to do: Enable Switchee to be nested inside itself.

       
lebisol's avatar
lebisol
2,234 posts
about 16 years ago
lebisol's avatar lebisol

Interesting….but isn’t ‘case’ the same load as the condition of ‘if’? Can you set variables value to be = weblog fields? and can it hold multiple values? {variable_to_test}= apples, oranges,plums or {variable_to_test} = 1,7,23,69

Thanks for sharing!

       
Mark Croxton's avatar
Mark Croxton
319 posts
about 16 years ago
Mark Croxton's avatar Mark Croxton
Interesting….but isn’t ‘case’ the same load as the condition of ‘if’?

No - {if} is parsed AFTER the various conditions contained within it have been parsed. So if you have 5 if:elseif conditions, all 5 will be parsed, before the 4 non-matching conditons are removed.

With my plugin set with parse=”inward”, only the matching condition will be parsed.

Can you set variables value to be = weblog fields?

Yes, if you are using it inside the exp:weblog tag.

{exp:weblog:entries}
{exp:switchee variable = "{my_custom_field}" parse="inward"}
    
    {case value="value1"}
        Content to show
    {/case}
    
    {case value="value2" default="Yes"}
        Content to show
    {/case}
    
    {case value="value3"}
        Content to show
    {/case}
    
{/exp:switchee} 
{/exp:weblog:entries}
and can it hold multiple values? {variable_to_test}= apples, oranges,plums or {variable_to_test} = 1,7,23,69

No - since we’re testing if each condition matches the variable - but I will be adding multiple case values very shortly: {case value="apples|oranges"}

Which makes more sense if you think about it 😊

       
lebisol's avatar
lebisol
2,234 posts
about 16 years ago
lebisol's avatar lebisol

Right right…in that case my hat of to you.😉 This can be very handy for those wanting the extra boost in performance {if} they are riding on lot of conditions such as extra large menu-navigation etc.

I wonder how it matches up to {if:else}:

{if field =='apple'}
Ummm apple pie...
{if:else}
D'ouh! Apply doughnut patch.
{/if}

Do tell!

Good stuff!

       
Joe Wolin's avatar
Joe Wolin
206 posts
about 16 years ago
Joe Wolin's avatar Joe Wolin

Great work. I really need this to support multiple case values as you noted would be coming soon.

Any chance you have this working yet?

{case value="apples|oranges"}
       
Mark Croxton's avatar
Mark Croxton
319 posts
about 16 years ago
Mark Croxton's avatar Mark Croxton

Done - download the latest version from the first post, it now supports multiple case values.

       
Rob Quigley's avatar
Rob Quigley
236 posts
about 16 years ago
Rob Quigley's avatar Rob Quigley

Hey Mark, this sounds great but the tag pairs you are using, “case,” are a little confusing to me. Would you mind drawing up a real world example showing how this works?

       
Mark Croxton's avatar
Mark Croxton
319 posts
about 16 years ago
Mark Croxton's avatar Mark Croxton

Switch/case, like if/else, is a common programming control statement; see for example: http://php.net/manual/en/control-structures.switch.php

Here’s a simple example. What I’m doing is showing either a list of headlines or a single story, depending on whether segment_2 exists. So my uris might look like:

Headlines view: mywebsite.com/news

Single story view: mywebsite.com/news/my-news-story

Switchee will check the value of {segment_2} to choose which case to show.

The first case is for when {segment_2} is equivalent to “” (an emtpy string)

The second case is the default case that will be shown if the first case doesn’t match.

{exp:switchee variable="{segment_2}" parse="inward"}
            
            {!-- Homepage view --}
            {case value=""}

                <!-- 10 headlines -->
                {exp:weblog:entries weblog="news" orderby="date" sort="desc" limit="10" disable="member_data|trackbacks|pagination|categories"}
                        <h4><a href="http://{title_permalink=news/index}">{title}</a></h4>
                        {summary}
                {/exp:weblog:entries}
                <!-- /10 headlines -->
                
            {/case}
            {!-- /Homepage view --}

            {!-- Single story view --}        
            {case default="Yes"}

                <!-- story -->
                    {exp:weblog:entries weblog="news" orderby="date" sort="desc" limit="1" disable="member_data|trackbacks|pagination"}

                        <h3><a href="http://{title_permalink=news/index}">{title}</a></h3>
                        
                        {summary}
                        
                        {body}

                        <dl class="metadata">
                            <dt>Posted by:</dt>
                            <dd><a href="http://{path=member/{author_id}}">{author}</a> on {entry_date format="%D, %F %d, %Y at %g:%i:%s %A"}</dd>
                            
                            <dt>Categories:</dt>
                            <dd>                    
                                {categories backspace="1"}
                                <a href="http://{path=news}">{category_name}</a>,
                                {/categories}
                            </dd>
                
                        </dl>
                    {/exp:weblog:entries}
                <!-- /story -->
                
            {/case}
            {!-- /Single story view --}
            
            {/exp:switchee}
       
Rob Quigley's avatar
Rob Quigley
236 posts
about 16 years ago
Rob Quigley's avatar Rob Quigley

Ahhh - I get it now. Thanks so much for drafting that! Great work on this plugin. I will use it for sure!

I’ve been using some php conditionals for URL segments and parsing on input so that the template doesn’t process those EE tags that are in the php conditional blocks that evaluate false.

But, occasionally, I need parsing on ouput or have conditional situations that only EE variables will work.

Hats off on this work!

       
Mark Croxton's avatar
Mark Croxton
319 posts
about 16 years ago
Mark Croxton's avatar Mark Croxton

Updated to version 1.2, which now supports regular expression matches within #hashes# and empty strings represented by ” or “”.

       
Mark Croxton's avatar
Mark Croxton
319 posts
about 16 years ago
Mark Croxton's avatar Mark Croxton

Updated to version 1.3.

  • Added support for reserved characters in regular expressions
  • Multiple regular expressions separated by | can now be used safely for one case value
       
Mark Croxton's avatar
Mark Croxton
319 posts
about 16 years ago
Mark Croxton's avatar Mark Croxton

Updated to version 1.4

  • fixed a minor bug
       
Joe Wolin's avatar
Joe Wolin
206 posts
about 16 years ago
Joe Wolin's avatar Joe Wolin

Mark,

I really like your plugin and your example for including page and entry views. What do you think is the best way to handle pagination in the case that the “home-page” view includes pagination? The pagination links would be directed into the story view.

       
Mark Croxton's avatar
Mark Croxton
319 posts
about 16 years ago
Mark Croxton's avatar Mark Croxton

Hi Joe, glad you like it!

to account for pagination (P0, P1, P3 etc) is actually pretty easy.

Let’s say you have a template viewable at www.my_site.com/template_group/template

A paginated page might look like www.my_site.com/template_group/template/P2

So the patterns we need to match in segment 3 are #^P(\d+)$# and ” (nothing)

We can use a pipe | to separate these patterns, so:

{exp:switchee variable="{segment_3}" parse="inward"}
            
    {!-- Index page. Match empty string or pagination --}
    {case value="#^P(\\d+)$#|''"}
        Index page
    {/case}
                
    {!-- Single entry --}
    {case default="yes"}
        Single entry
    {/case}
                
{/exp:switchee}

if you also wanted to filter your index page entries by date, so that your urls look like:

www.my_site.com/template_group/template/2010/02

Or when paginated:

www.my_site.com/template_group/template/2010/02/P2

You could instead use this as your first case value:

{case value="#^P(\\d+)$#|''|#^(\\d& #123;4& #125;)$#"}

(remove the spaces between the & and the # in the pattern)

       
Joe Wolin's avatar
Joe Wolin
206 posts
about 16 years ago
Joe Wolin's avatar Joe Wolin

perfect… thanks Mark!

       
1 2 3

Reply

Sign In To Reply

ExpressionEngine Home Features Pro Contact Version Support
Learn Docs University Forums
Resources Support Add-Ons Partners Blog
Privacy Terms Trademark Use License

Packet Tide owns and develops ExpressionEngine. © Packet Tide, All Rights Reserved.