问题
I have assigned a variable based on the number of characters in a name, which returns an integer (1,2,3, etc). I would like to further add an {if} statement to show an option if the option name matches the variable. The option names are 5" x 7" - 1, 5" x 7" - 2, 5" x 7" - 3 etc.
{assign var="numberofcharacters" value=$smarty.get.name|count_characters}
{if $vr.variant_name == '5" x 7" - $numberofcharacters' || $vr.variant_name == '8" x 11" - $numberofcharacters'}
...
{/if}
This is not producing a result, even though I have 3 options that should be showing. Please could somebody let me know what is wrong with my {if} statement?
I cannot use:
{if $vr.variant_name|contains:}
because if the value returned is 1, then 10, 11 and 12 are also included when I just need 1 included.
MANY THANKS
回答1:
Smarty3 with escaped quotes:
{$numberofcharacters = 1}
{$var = "5\" x 7\" - {$numberofcharacters}"}
{$var}
or
{$numberofcharacters = 1}
{$name = '5" x 7"'}
{$var = "{$name} - {$numberofcharacters}"}
{$var}
or Smarty2
{assign var="numberofcharacters" value=1}
{assign var="name" value='5" x 7"'}
{assign var="var" value="`$name` - `$numberofcharacters`"}
{$var}
or using the cat modifier
{assign var="numberofcharacters" value=1}
{assign var="name" value='5" x 7"'}
{assign var="var" value=$name|cat:" - "|cat:$numberofcharacters}
{$var}
throwing things together should be easy enough…
{$numberofcharacters = 1}
{$five_seven = "5\" x 7\" - {$numberofcharacters}"}
{$eight_eleven = "8\" x 11\" - {$numberofcharacters}"}
{if $vr.variant_name == $five_seven || $vr.variant_name == $eight_eleven}
…
{/if}
But… If you have a fixed pattern you want to check, you might want to use a regular expression instead? or a substr?
{$variant_name = '5" x 7" - 123'}
{if preg_match('/^5" x 7"|^8" x 11"/', $variant_name, $tmp)}
hello world
{/if}
(you should do stuff like that in your PHP though…)
回答2:
Smarty isn't parsing this:
'5" x 7" - $numberofcharacters'
as you expect.
http://www.smarty.net/docs/en/language.function.capture.tpl
{assign var="numberofcharacters" value=$smarty.get.name|count_characters}
{capture c1 assign=test1}5" x 7" - {$numberofcharacters}{/capture}
{capture c1 assign=test2}8" x 11" - {$numberofcharacters}{/capture}
{if $vr.variant_name==test1 || $vr.variant_name==test2}
...
来源:https://stackoverflow.com/questions/9279588/smarty-if-statement-syntax