mustache icon indicating copy to clipboard operation
mustache copied to clipboard

Support for recursive partials

Open deuill opened this issue 11 years ago • 4 comments

Mustache supposedly allows for recursive partials, which are useful for rendering nested/heirarchical data like trees and lists etc.

I think this might be somewhat hard to accomplish due to the fact we compile/parse the template before we render it, so partials are evaluated even if they're wrapped in sections which are empty.

Is there some way around this? Any planned support?

deuill avatar Jan 09 '13 10:01 deuill

Is it in the mustache spec (does hogan.js or the ruby mustache library have this feature)?

abh avatar Apr 03 '13 04:04 abh

I must admit recursive partials do seem a bit strange to me, but I can imagine a use case.

hoisie avatar Apr 07 '13 19:04 hoisie

It's supported in the canonical Ruby implementation, which has a test case for recursive partials. They're useful for data structures with arbitrary depths, such as category lists etc, and help keep the code clean. For example:

category.mustache

<div class="category">
  <div class="name">{{name}}</div>
  {{#sub}}
  {{> category}}
  {{/sub}}
</div>

data.json

[
    {
        "name": "Birds",
        "sub": [
            {
                "name": "Corvidae",
                "sub": [
                    {
                        "name": "Crows"
                    },
                    {
                        "name": "Ravens"
                    },
                    {
                        "name": "Rooks"
                    }
                ]
            },
            {
                "name": "Chickens"
            }
        ]
    },
    {
        "name": "People"
    }
]

The above example would be much dirtier and would not cover all test cases if not for recursive partials. I guess one solution would be to parse each partial seperately during compilation and inserting them conditionally in the rendering phase.

deuill avatar Apr 12 '13 09:04 deuill

Nice example @thoughtmonster ! This should definitely be supported. The parsing is recursive, so there might be a quick solution if can some how mark partials as already visited.

hoisie avatar Apr 12 '13 13:04 hoisie