hoisie / mustache

The mustache template language in Go
MIT License
1.11k stars 225 forks source link

Support for recursive partials #26

Open deuill opened 11 years ago

deuill commented 11 years ago

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?

abh commented 11 years ago

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

hoisie commented 11 years ago

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

deuill commented 11 years ago

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.

hoisie commented 11 years ago

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.