mustachemustache.php

Can I use a Mustache var in a partial name?


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}}

Solution

  • 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.