2010-02-11 86 views
32

我想知道是否有可能將一個數組分配給一個Smarty模板文件中的變量?我已經試過這如何在smarty模板文件中分配數組?

{assign var='file' value = array('dir','doc','exe')} 

但是,當我打印出來的陣列它會產生這樣的:

array(\'dir\',\'doc\',\'exe\') 

如何停止的Smarty逃避數組值?

在此先感謝

+0

我曾經使用過此問題,並跑了一個解決方案來得更早了。我想出的解決方案是[這裏](http://stackoverflow.com/questions/11336840/shorten-smarty-if-statements/11337280) – Subash 2012-07-05 02:48:57

回答

44
{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

+1

如果你使用{php},那麼使用smarty的含義是什麼?你不應該在模板內使用{php},除非它是唯一的選擇。 @Jenski的解決方案非常完美 – 2015-07-02 06:49:41

+1

請確保不要在最後一個元素後面加一個逗號(,)。我是從PHP複製數組,這是導致語法錯誤。 – rambii 2018-02-02 10:50:54

42

我剛剛發現了另一個答案here允許你不需要使用{php} tags(由Smarty推薦)

{assign var='icon' value=','|explode:"dir,doc,exe"} 

到更多的想法,雖然仍處於打開狀態...

+0

此方法不允許分配關聯數組 – Kirzilla 2010-02-11 13:41:35

+0

+1 - 謝謝。這正是我們在我們的第三方CMS中解決問題所需要的。 – 2010-04-23 22:33:57

+0

對於smarty的第3版,請參閱Mituha的答案。 – Andy 2012-10-23 11:50:03

8

{$system=['freebsd','windows','macosx','linux']}什麼?

+1

這適用於Smarty v3:http://www.smarty.net/docs/en/language.syntax.variables.tpl – Andy 2012-10-23 11:48:58

-1

它不正確的方式來寫在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} 
+2

請解釋它爲什麼不正確。 – 2015-08-14 15:37:02

0
$smarty->assign("lat",$lat); 

{foreach $lat as $latlongval} 
    {assign var="myArray" value=","|explode:$latlongval} 
    {$myArray['0']} 
    {$myArray['1']} 
{/foreach}