php 如何在 smarty 模板文件中分配数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2244319/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to assign an array within a smarty template file?
提问by Jenski
I was wondering if it was possible to assign an array to a variable within a Smarty template file? I have tried this
我想知道是否可以将数组分配给 Smarty 模板文件中的变量?我试过这个
{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?
如何阻止 Smarty 转义数组值?
Thanks in advance
提前致谢
回答by Kirzilla
{php}
$this->assign("array", array('dir','doc','exe'));
{/php}
{foreach from=$array item=item}
{$item}
{/foreach}
From Smarty v.3new syntax is available
从Smarty v.3新语法可用
{$array = ['item1','item2',$item3]}
see for more details : http://www.smarty.net/docs/en/language.syntax.variables.tpl
有关更多详细信息,请参阅:http: //www.smarty.net/docs/en/language.syntax.variables.tpl
回答by Jenski
I just found another answer herethat allows you to do this without the use of {php} tags(recommended by Smarty)
我刚刚在这里找到了另一个答案,它允许您在不使用{php} 标签的情况下执行此操作(Smarty 推荐)
{assign var='icon' value=','|explode:"dir,doc,exe"}
still open to more ideas though...
尽管如此,仍然对更多想法持开放态度......
回答by Mituha Sergey
what about {$system=['freebsd','windows','macosx','linux']}?
怎么样{$system=['freebsd','windows','macosx','linux']}?
回答by Mituha Sergey
$smarty->assign("lat",$lat);
{foreach $lat as $latlongval}
{assign var="myArray" value=","|explode:$latlongval}
{$myArray['0']}
{$myArray['1']}
{/foreach}
回答by RaJeSh
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.
在 smarty 模板文件中编写代码不是正确的方法。您应该在 php 中创建一个数组,然后从 smarty 获取值。
This is the right way to create a standard development code. like.
PHP:
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}

