I would like to render a tree with an undetermined depth (children of children of children, etc.). I need to loop through the array recursively; how can I do this in Twig?
相关问题
- PHP Recursively File Folder Scan Sorted by Modific
- R: eval(parse()) error message: cannot ope
- Highlight parent path to the root
- Avoid overlapping of nodes in tree layout in d3.js
- Get path of node in tree
相关文章
- Creating a list of functions using a loop in R
- AttributeError: 'Series' object has no att
- Recursively replace keys in an array
- Python: Maximum recursion depth exceeded when prin
- Is recursion good in SQL Server?
- How does this list comprehension over the inits of
- Find all subfolders of the Inbox folder using EWS
- What is the Twig equivalent of isset() and !empty(
The answers here lead my to my Solution.
I have a Category Entity with self referencing ManyToOne association (parent to children).
In my twig template i am rendering the tree view like this:
Took flu's answer and modified it a little:
If you're running PHP 5.4 or higher, there is a wonderful new solution (as of May 2016) to this problem by Alain Tiemblo: https://github.com/ninsuo/jordan-tree.
It's a "tree" tag that serves this exact purpose. Markup would look like this:
First i thought, this may be solved straightforward - but it isn't that easy.
You need to create a logic, maybe with a php class method, when to include a twig subtemplate and when not.
So you could use the special twig loop variable , which is available inside a twig for loop. But i'm not sure about the scope of this loop variable.
Sorry for provide only an approach not a solution, but perhaps i hope my thoughts may help you (a little bit).
This and other informations are available on Twigs "for" Docu !
If you want to use a Macro in the same template you should use something like this to stay compatible with Twig 2.x:
This extends
random-coder
's answer and incorporatesdr.scre
's hint to the twig documentation about macros to now use_self
but import locally.Thanks domi27, I played around with your idea and came up with this. I made a nested array as my tree, ['link']['sublinks'] is null or another array of more of the same.
Templates
The sub-template file to recurse with:
Then in the main template call this (kinda redundant 'with' stuff there):
Macros
A similar effect can be achieved with macros:
In the main template do this:
Hope it helps :)