Possible Duplicate:
Symfony2 Twig unlimited child depth
I want to loop though a list of objects within Twig. The list has some sort of a self-referenced many-to-one relationship and can look like this:
- Item 1
- Item 2
- Item 2 1
- Item 2 2
- Item 2 2 1
- Item 3
- Item 3 1
- Item 4
So the definition within the entity looks like:
/**
* @ORM\OneToMany(targetEntity="Item", mappedBy="parent")
*/
private $children;
/**
* @ORM\ManyToOne(targetEntity="Item", inversedBy="children")
* @ORM\JoinColumn(name="parent_id", referencedColumnName="id")
*/
private $parent;
I know want to create a list like from within twig like:
<ul>
<li>Item 1</li>
<li>
Item 2
<ul>
<li>Item 2 1</li>
<li>
Item 2 2
<ul>
<li>Item 2 2 1</li>
</ul>
</li>
</ul>
</li>
<li>
Item 3
<ul>
<li>Item 3 1</li>
</ul>
</li>
<li>Item 4</li>
</ul>
How can this be done?
There are several ways of doing this in Twig. A very easy one is using a macro that is called recursively. This macro can be placed within the same file as the actual output and is referenced through:
{{ _self.macroname(parameters) }}See comments for detailed explanation:
The only thing, that is left to do, is to call the macro from within the template one time:
Hope, somebody finds this useful, too.