Published by Mijingo

tips icon image

EE Insider Tips
Sponsored by Mijingo's EE 2 Screencasts

ExpressionEngine mini-howtos created by the EE Insider community.

Make assign_variable conditional

User's avatar
  • Posted by johnniefp
  • June 01, 2009
  • 4 people have found this tip helpful.

I’m sure we all use assign_variable at the top of our templates, with a name like assign_variable you’d think you could do something like this:

{if segment_2 == ""}
  {assign_variable
:my_weblog="apples"}
{if
:else}
  {assign_variable
:header_image="{segment_2}"}
{
/if} 

Well you can’t! if you read the docs is stats the following:


Note to developers: In this context, the word “variable” is used simply to mean the use of an ExpressionEngine style variable in the template to substitute for some other text. It is not a “variable” in the sense of being an accessible and modifiable value held in memory. It is a simple text replacement that occurs the moment the Assign Variable tag is encountered by the template parser.


So remember: assign_variable as immutable

PHP to the rescue though.
Turn on “Allow PHP” for your template in CP Home > Templates > Template Preferences Manager
Set the “PHP Parsing Stage” to “Input” also in CP Home > Templates > Template Preferences Manager

You can then do something like this:

<?php
  
global $IN;

  
$segment $IN->fetch_uri_segment(2);
  if(
$segment == ""{

    
echo "{assign_variable:my_weblog='apples'}";
  
else {

    
echo "{assign_variable:my_weblog='$segment'}";
  
}
?> 
Robert @ SD03:09 on 12.31.2010

Hi, I believe assign_variable is replaced by preload_replace in EE 2.0; but it seems that the php code given does not work in EE 2.0. How can I do this in EE 2.0 with preload_replace tag?
Thanks!

Add Your Comment?

You must have an EE Insider account to post comments on Insider Tips. It's fast, easy and hassle-free.

Sign up now (or login).

Search EE Insider Tips
Sponsored By