Martin Sowning
Martin Sowning

Reputation: 393

Nested list with TWIG in Symfony 2

i have in database

Category:
id | name
1  | first
2  | second
etc

and:

News:
id | category | name
1  | 1        | one
2  | 2        | two
3  | 1        | three
4  | 2        | four
5  | 2        | five

ETC.

how is the best method for show this in TWIG?

FIRST
- one
- three
SECOND
- two
- four
- five

etc.

in Symfony 1.4 i can use get data from template PHP, but in Symfony 2 i must get all data in controllor, but how?

Upvotes: 0

Views: 1148

Answers (2)

domi27
domi27

Reputation: 6923

So you have a working relation between Category and News, it is working straightforward.

// Class Category
/**
 * Relation to News
 * 
 * @ORM\OneToMany(targetEntity="News", mappedBy="news")
 */
private $news;
public function getNews()
{
    return $this->news;
}

So you pass the category object(s) from controller to your template, and TWIG converts the "category.news" towards the Category->getNews() function.

{% for newsitem in category.news %}
    <p>{{ newsitem.id }}</p>
{% endfor %}

You may find further information on this "variable/function handling": http://twig.sensiolabs.org/doc/templates.html#variables

Upvotes: 3

Maerlyn
Maerlyn

Reputation: 34105

I'm not using Sf2 (yet) so I can't give you exactly what you need, but it should be similar to this:

  • in your controller, get all categories, inner joining with the relation to news (to make sure a single query is used to get all the data needed)
  • in your template, do a for on the categories
  • in that loop, do a for on the current category's relation to news

Upvotes: 1

Related Questions