Claudiu
Claudiu

Reputation: 3261

PHP - Mustache partials in a loop

I see Mustache as being great because it allows partials and it's also relatively lightweight comparing to Smarty for example. My idea of using Mustache is: define a set of partials that constitute an UI library. Pass data in those partials and use them like you would use html elements on steroids.

An example of a partial would be a list element (visually). From a markup point of view that element is defined as a 20 lines HTML block. I want to use that partial in a loop or I might want to use it independently.

If I want to build a list containing the mentioned partial, I would do so like this:

{{#my_list_elems}}
 ... Maybe some HTML code
 {{> my_partial
{{/my_list_elems}}

Let's say my_partial looks like this:

<div>
  <ul>
  {{#another_array}}
    <li>{{name}}</li>
  {{>#another_array}}
  </ul>
</div>

Now, after a couple of hours of trying to figure this out, my main template looks more or less like this:

{{> head}}
{{> header}}
<div>Some static HTML</div>
... More code
{{#some_array}}
{{> my_partial}}
{{/some_array}}
{{> footer}}

Problem: For some reason, this doesn't work for me. I tried rendering the partial individually, it works. An array though? Meh.

Also, I'm having a hard time figuring out, if I do get it to work, how will it handle variables. At the moment, I'm rendering it like this:

$template = $this->mustache->loadTemplate('template');
$partials['my_partial'] = $this->mustache->loadPartial('my_partial');
$data['my_partial_arr'] = $this->getPartialData();

echo $template->render($data, $partials);

Note that the PHP code and partial example aren't meant to work together, they're just that, examples.

Question is, is this feature supported? If yes, what am I doing wrong? Maybe my PHP array doesn't have the proper format? I could have the array/loop at a lower level, in the partial, but that kind of makes it ugly-ish when I want to use the partial by itself (Wrapping data in a one elem array so it renders).

Upvotes: 2

Views: 2273

Answers (1)

bobthecow
bobthecow

Reputation: 5117

So the {{> head }}, {{> header }} and {{> footer }} partials work, but {{> my_partial }} doesn't? Are you using a filesystem partials loader, or passing partials to the Mustache constructor as strings?

Two things which could be catching you:

  1. Mustache might not consider your array (my_partial_arr) to be "iterable". The Mustache.php wiki has a bit more on that. You can run 'em through array_values() to ensure that they'll be looped over rather than used as a section context.

  2. You can't pass partials to the render() call on a mustache template.

    In most cases, passing partials as a second argument won't cause a problem, since that function doesn't take a second argument anyway... it'll simply load any necessary partials via loadPartial() on your Mustache instance anyway.

Upvotes: 3

Related Questions