41

I was wondering if it was possible to assign an array to a variable within a Smarty template file? I have tried this

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

But when I print out the array it produces this:

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

How can I stop Smarty escaping the array values?

starball
  • 20,030
  • 7
  • 43
  • 238
Jenski
  • 1,458
  • 1
  • 18
  • 29
  • I have ran through this problem and came up with a solution earlier. The solution I came up with is [here](http://stackoverflow.com/questions/11336840/shorten-smarty-if-statements/11337280) – Subash Jul 05 '12 at 02:48

5 Answers5

53
{php}
  $this->assign("array", array('dir','doc','exe'));
{/php}

{foreach from=$array item=item}
  {$item}
{/foreach}

From Smarty v.3 new syntax is available

{$array = ['item1','item2',$item3]}

see for more details : http://www.smarty.net/docs/en/language.syntax.variables.tpl

Kirzilla
  • 16,368
  • 26
  • 84
  • 129
  • 1
    If you use {php} then what is the meaning of using smarty? You should not use {php} inside template until it is the only option. @Jenski 's solution is perfect – Vipul Hadiya Jul 02 '15 at 06:49
  • 1
    Make sure NOT to put a comma (,) behind the last element. I was copying the array from php which was causing an syntax error. – rambii Feb 02 '18 at 10:50
  • It is also possible to assign variable manually to template vars: {php}$this->_tpl_vars['my_array'] = ['var1', 'var2'];{/php} – Robert Jan 24 '22 at 17:03
45

I just found another answer here that allows you to do this without the use of {php} tags (recommended by Smarty)

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

still open to more ideas though...

Jenski
  • 1,458
  • 1
  • 18
  • 29
9

what about {$system=['freebsd','windows','macosx','linux']}?

DaveShaw
  • 52,123
  • 16
  • 112
  • 141
Mituha Sergey
  • 444
  • 6
  • 4
  • 1
    This works in Smarty v3: http://www.smarty.net/docs/en/language.syntax.variables.tpl – Andy Oct 23 '12 at 11:48
0

its not right way to write a code with in smarty template file. you should create a array in php and then get the values from 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}
RaJeSh
  • 313
  • 3
  • 14
0
$smarty->assign("lat",$lat);

{foreach $lat as $latlongval}
    {assign var="myArray" value=","|explode:$latlongval} 
    {$myArray['0']}
    {$myArray['1']}
{/foreach}
nhahtdh
  • 55,989
  • 15
  • 126
  • 162