Can I use a Mustache var in a partial name?

2.2k Views Asked by At

I currently use a template for multiple pages (basic.mustache) and everything work great, but I want to add different boxes (box1.mustache, box2.mustache) in a sidebar depending of the page.

Basically, I would need to add the mustache templates in the object parsed by the template.

{
  title: "My page tile",
  content: ...
  sidebar: [
    "box1.mustache",
    "box2.mustache"
  ]
}

but how can I do something equivalent to this in the main template (basic.mustache) ?

{{#sidebar}}
  {{>.}}
{{/sidebar}}
3

There are 3 best solutions below

3
bobthecow On BEST ANSWER

No, it's not possible to do like that. But it's still possible to accomplish what you're looking for. See this answer for one answer.

Looking at your example, though, I think what you're looking for is better addressed by template inheritance (the BLOCKS pragma).

So you'd have layout.mustache as your "parent" template:

<!DOCTYPE html>
<html>
  <head>
    <title>{{$ title }}My site has a title!{{/ title }}</title>
  </head>
  <body>
    <section id="main">
      {{$ content }}{{/ content }}
    </section>
    <section id="sidebar">
      {{$ sidebar }}{{/ sidebar }}
    </section>
  </body>
</html>

And my_page.mustache as your "page" template:

{{< layout }}

  {{$ title }}This page has its own title!{{/ title }}

  {{$ sidebar }}
    {{> box1 }}
    {{> box2 }}
  {{/ sidebar }}

  {{$ content }}
    Here's all your awesome content!
  {{/ content }}

{{/ layout }}

Notice how my_page loads box1 and box2 partials into the {{$ sidebar }} block. You could even have default sidebar partials by adding them to the {{$ sidebar }} block in the main layout (just like there's a default {{$ title }}).

Note that BLOCKS is a pragma, and as such is not enabled by default in Mustache.php. To use it, you either have to add {{% BLOCKS }} to the first line of any template with blocks in it, or pass ['pragmas' => [Mustache_Engine::PRAGMA_BLOCKS]] to the Mustache_Engine constructor to enable them globally.

0
Gwendal Roué On

Some Mustache implementations answer to this frequent question with support for "dynamic partials". See https://github.com/thelucid/tache (Ruby) and https://github.com/groue/GRMustache/blob/master/Guides/rendering_objects.md#example-dynamic-partials (Objective-C).

0
Randy Hall On

If you build the string ahead like so

... part: "{{>" + MyPartialName + "}}"

then use in your template like so

{{>part}}

It appears to work. I haven't tested this in the original JS implementation yet (using .net), so some confirmation would be nice.