Smarty 'if' statement syntax

走远了吗. 提交于 2019-12-22 14:43:50

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!