How to use function wrapper in mustache.php?

瘦欲@ 提交于 2019-12-11 00:08:16

问题


I'm starting to work with Mustache on PHP and I don't manage to make wrapper functions to work as debt.

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 render m.render($tenplate, $data); and I would like to obtain something like:

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

But it doesn't work.

I get

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

Because Mustache is passing "{{skill_level}}"to my function instead of value 3.

Furthermore if I change the template a put backspaces in the mustache labels:

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

Then {{ skill_level }} is processed but it isn't sent to {{ #starts }}, the render obtained is

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

So, does anybody know what I'm doing wrong? How should I wrote the template to make it works? Any advice or experience are welcome. Thanks.


回答1:


I have found the answer in the wiki of the project

The text passed is the literal block, unrendered.

But it provides a Mustache_LambdaHelper that can be used to render the text passed.

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 that's all it's needed to make it works. Thanks to all readers!



来源:https://stackoverflow.com/questions/17195443/how-to-use-function-wrapper-in-mustache-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!