25

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

0

5 Answers 5

34

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.
14

It's actually very simple:

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

2 Comments

Does it work with version 2 ?
@SébastienGarcia-Roméo Unfortunately not.
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.

2 Comments

I don't like the first approach, because of "inline" php code. The second solution is a bit tricky but is still valid smarty without any hacks. Voted up!
and it works with smarty-v2!
1

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

Comments

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.

4 Comments

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 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> 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 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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.