How do I use a wrapper function in a mustache.php file?

I am getting started with Mustache in PHP and I am having trouble getting the wrapper functions to work like promissory notes.

I have this template

{{#skill_level}}
  <span class="stars">
    {{#stars}}
      {{skill_level}} 
    {{/stars}}                        
  </span>
{{/skill_level}}

      

And I have this data

$data = new StdClass;
$data->skill_level = 3;
$data->stars = function($level) {
  $aux = "";
  $l = intVal($level);
  for ($i = 0; $i < $l; $i++) {
    $aux .= "+";
  }
  for ($i = $l; $i < 5; $i++) {
    $aux .= ".";
  }
  return $aux;
};

      

I am drawing m.render($tenplate, $data);

and I would like to get something like:

<span class="stars">
    +++..                        
</span>

      

But that won't work.

I get

<span class="stars">
    .....                        
</span>

      

Because it Mustache

passes "{{skill_level}}"

my function instead of a value 3

.

Also, if I change the template, put the backspaces in the mustache labels:

{{ #skill_level }}
  <span class="stars">
    {{ #stars }}
      {{ skill_level }} 
    {{ /stars }}                        
  </span>
{{ /skill_level }}

      

Then {{ skill_level }}

processed, but not sent to {{ #starts }}

, the resulting render

<span class="stars">
    3                        
</span>

      

So, does anyone know what I am doing wrong? How do I write a template to make it work? Any advice or experience is appreciated. Thank.

+2


source to share


1 answer


I found the answer on the project wiki

The passed text is a literal block, unrendered.

But it does provide Mustache_LambdaHelper

which can be used to render the passed text.



So I have to add this to my lambda function:

$data->stars = function($label, Mustache_LambdaHelper $helper) {     
  $aux = "";
  $level = $helper->render($label);
  $l = intVal($level);
  for ($i = 0; $i < $l; $i++) {
    $aux .= "+";
  }
  for ($i = $l; $i < 5; $i++) {
    $aux .= ".";
  }
  return $aux;
};

      

And whatever it takes to make it work. Thanks to all readers!

+6


source







All Articles