23

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

sachin sawant
  • 231
  • 1
  • 2
  • 3

5 Answers5

33

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.

rodneyrehm
  • 13,442
  • 1
  • 40
  • 56
  • 3
    I have tried this advice and it works. This feature does not appear to be documented in Smarty documentation, which makes this advice even more valuable to me. – Sergei G Feb 03 '13 at 04:32
14

It's actually very simple:

{assign 'myArray' ['cat', 'dog', 'rabbit']}
Eugene Kuzmenko
  • 947
  • 9
  • 11
13

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.

DerVO
  • 3,679
  • 1
  • 23
  • 27
1

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

Jeremy
  • 1,878
  • 2
  • 30
  • 54
1

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.

Catalin
  • 858
  • 5
  • 16
  • And how do you process a table (with rows) in a Model so that there wouldn't be any HTML markup? You still have to pass whole array of data and build dynamic table from it in the view. – Andrew Jan 26 '14 at 10:32
  • @Andrew Am I missing something in my answer? I didn't say the view has to be static, I only pointed out that all the data processing should be done in the model and passed to the view to be displayed. – Catalin Jan 27 '14 at 11:45
  • Catalin> Yeah, i understand what you mean. I just wanted to know if there is a way to prevent loop in template. And AFAIK there isn't any... – Andrew Jan 28 '14 at 07:58
  • @Andrew well you could but it wouldn't be effective. You could for example loop a function which renders only one row of the table or something like that. – Catalin Jan 30 '14 at 08:22