我想知道是否有可能將一個數組分配給一個Smarty模板文件中的變量?我已經試過這如何在smarty模板文件中分配數組?
{assign var='file' value = array('dir','doc','exe')}
但是,當我打印出來的陣列它會產生這樣的:
array(\'dir\',\'doc\',\'exe\')
如何停止的Smarty逃避數組值?
在此先感謝
我想知道是否有可能將一個數組分配給一個Smarty模板文件中的變量?我已經試過這如何在smarty模板文件中分配數組?
{assign var='file' value = array('dir','doc','exe')}
但是,當我打印出來的陣列它會產生這樣的:
array(\'dir\',\'doc\',\'exe\')
如何停止的Smarty逃避數組值?
在此先感謝
{php}
$this->assign("array", array('dir','doc','exe'));
{/php}
{foreach from=$array item=item}
{$item}
{/foreach}
從Smarty的第3節新的語法可用
{$array = ['item1','item2',$item3]}
詳情參見:http://www.smarty.net/docs/en/language.syntax.variables.tpl
如果你使用{php},那麼使用smarty的含義是什麼?你不應該在模板內使用{php},除非它是唯一的選擇。 @Jenski的解決方案非常完美 – 2015-07-02 06:49:41
請確保不要在最後一個元素後面加一個逗號(,)。我是從PHP複製數組,這是導致語法錯誤。 – rambii 2018-02-02 10:50:54
我剛剛發現了另一個答案here允許你不需要使用{php} tags(由Smarty推薦)
{assign var='icon' value=','|explode:"dir,doc,exe"}
到更多的想法,雖然仍處於打開狀態...
約{$system=['freebsd','windows','macosx','linux']}
什麼?
這適用於Smarty v3:http://www.smarty.net/docs/en/language.syntax.variables.tpl – Andy 2012-10-23 11:48:58
它不正確的方式來寫在smarty模板文件中的代碼。你應該在php中創建一個數組,然後從smarty獲取值。
This is the right way to create a standard development code. like.
PHP:
public function arrSam(){
$colors = array(0 => '#1f1f1f', 1 => '#696969', 2 => '#878787', 3 => '#b4b4b4', 4 => '#d2d2d2', 5 => '#f0f0f0', 6 => '#ffffff');
$smarty->assign('colors', $colors);
}
Smarty的:
{assign var=colors value=$smarty->arrSam()}
{$colors|print_r}
請解釋它爲什麼不正確。 – 2015-08-14 15:37:02
$smarty->assign("lat",$lat);
{foreach $lat as $latlongval}
{assign var="myArray" value=","|explode:$latlongval}
{$myArray['0']}
{$myArray['1']}
{/foreach}
我曾經使用過此問題,並跑了一個解決方案來得更早了。我想出的解決方案是[這裏](http://stackoverflow.com/questions/11336840/shorten-smarty-if-statements/11337280) – Subash 2012-07-05 02:48:57