Create an array in smarty template? [duplicate]

2019-04-18 18:18发布

问题:

This question already has an answer here:

  • How to assign an array within a smarty template file? 5 answers

I need to create a new array from other one dimensional array in smarty template. So, what are the best possibilities to create an array in template file.

Thanks, Sachin

回答1:

Smarty3 allows you to {$var = ['foo' => 'bar', 'sub' => [1, 2, 3]]} and {$var.foo = 'other'}

if those options don't suffice, write a plugin function.



回答2:

In the past, I have used two approaches - an evil and a dirty one - to quickly assign an array inside a tpl:

{* Am I evil? *}
{php}
    $array = array("cat", "dog", "rabbit");
    $this->assign("myArray", $array);
{/php}

{* Am I dirty? *}
{assign var='myArray' value=','|explode:"cat,dog,rabbit"}

Both result in your array available inside the template to build a simple loop. Anyway I always ended up changing my code this way, so I did not need this stuff at all.



回答3:

It's actually very simple:

{assign 'myArray' ['cat', 'dog', 'rabbit']}


回答4:

I advise against this but this plugin allows this: http://smarty.incutio.com/?page=set



回答5:

From a MVC point of view, the View part of it is only responsible with displaying the data. I would encourage you to rethink the application in such a way that it will allow you to process the data in the Model and pass it for display only in the View.



标签: php smarty