使用Smarty 2在一行上分配变量值

I am using Smarty 2 and wondered if there is a better/tidier way to use assign to set the value of evenRow on one line, rather than the 5 lines below.

{if $evenRow == 'on'}
   {assign var='evenRow' value='off'}
{else}
   {assign var='evenRow' value='on'}
{/if}

Considering Smarty can be quite closely aligned with PHP in places i'm surprised this isn't easily found online, as doing something like this in PHP would be straightforward.

From Smarty documentation (Smarty 3):

Although Smarty can handle some very complex expressions and syntax, it is a good rule of thumb to keep the template syntax minimal and focused on presentation. If you find your template syntax getting too complex, it may be a good idea to move the bits that do not deal explicitly with presentation to PHP by way of plugins or modifiers.

What they are basically suggesting is that you should keep the amount of logic in the templates down and use functions or modifiers instead. For simple cases you can use simple expressions as attribute values:

{assign var=test_var value=!empty($some_input)}

For more complex examples, you can write your own modifier:

function smarty_modifier_do_something_complex($input) {
  // Process input and return value
}

and use it like this:

{assign var=test_var value=$some_input|do_something_complex}

Or you can stick with a more verbose {if} … {else} … {/if} approach.

I created a plugin for that:

modifier.choice.php

function smarty_modifier_choice()
{
    $no_choice="";
    $args=func_get_args();
    $patro=$args[0];
    $numconds=sizeof($args)-1;


    if ($numconds%2) {$no_choice=$args[$numconds];}

    for ($i=1;$i<$numconds; $i+=2)
    {
        if ($patro==$args[$i]) {return $args[$i+1];}
    }
    return $no_choice;
}

save it to your smarty/plugins folder and use it like this:

{$variable|choice:'1':'one':'2':'two':'3':'three':'another number'}

if the last string is unpaired it assumes it's the default value, but you can also use the default modifier:

{$variable|choice:'1':'one':'2':'two':'3':'three'|default:'another number'}

so if $variable is "1" it will return "one" and if it's "6" will return "another number"

in your case it would be like:

{assign var='evenRow' value=$evenRow|choice:'on':'off':'on'}

You can't make assign be something other than an assign.

Don't use assign. Use cycle.

{cycle  assign='evenRow' values="off,on"}