Goje87
Goje87

Reputation: 2869

How to change mustache template data dynamically

I have just started working with Mustache template engine. I am currently using PHP implementation of it (https://github.com/bobthecow/mustache.php/wiki). I am using helpers to manipulate the way data is rendered.

$data = array("name" => "abhilash");
$template = "Hello {{name}}, {{#bold}}Welcome{{/bold}}";

$m =  new Mustache_Engine(array(
  "helpers" => array(
    "bold" => function($content) {
      return "<b>$content</b>";
    })));
$html = $m->render($template, $data);

With the help of this I am able to render 'Welcome' with bold font. I would like to know if it is possible to manipulate $data with the help of helper function. For example if the template is like below and I have a helper function registered as dataSource, I would like to use it to collect some data (say key-value pair) from datasource_func_name() and append it to $data.

{{#dataSource}}datasource_func_name{{/dataSource}}
Hi {{name}}

Upvotes: 0

Views: 2059

Answers (1)

laurent
laurent

Reputation: 90746

That's normally not how you would use helpers. However, Mustache basically expects a data souce, so why not inject it directly?

$html = $m->render($template, $dataSource);

Upvotes: 1

Related Questions