Search code examples
phpjsontemplate-enginemustache.php

Mustache.php with JSON data throws Catchable fatal error


I've found out you can convert JSON file to PHP arrays and objects and use that output as a data for Mustache.php template engine like this example:

PHP Script:

require_once('Mustache/Autoloader.php');
Mustache_Autoloader::register();
$mustache = new Mustache_Engine();

$data_json = file_get_contents('data.json');
$data = json_decode( $data_json, true );
$template = $mustache -> loadTemplate('templates/template.html');
echo $mustache -> render( $template, $data );

JSON data:

{

    "persons": [{   
        "person": {
            "name": "Homer",
            "number": 0
        },
        "person": {
            "name": "Marge",
            "number": 1
        }
    }]

}

Mustache template:

{{{# persons }}}
{{{# person }}}
<ul>
    <li>Name: {{name}}</li>
    <li>Number: {{number}}</li>
</ul>
{{{# person }}}
{{{/ persons }}}

But PHP throws this error:

Catchable fatal error:
Object of class __Mustache_12af6f5d841b135fc7bfd7d5fbb25c9e could not be converted to string in C:\path-to-mustache-folder\Engine.php on line 607

And this is where PHP points that error came from (Inside Engine.php file in above error):

/**
 * Helper method to generate a Mustache template class.
 *
 * @param string $source
 *
 * @return string Mustache Template class name
 */
public function getTemplateClassName($source)
{
    return $this->templateClassPrefix . md5(sprintf(
        'version:%s,escape:%s,entity_flags:%i,charset:%s,strict_callables:%s,pragmas:%s,source:%s',
        self::VERSION,
        isset($this->escape) ? 'custom' : 'default',
        $this->entityFlags,
        $this->charset,
        $this->strictCallables ? 'true' : 'false',
        implode(' ', $this->getPragmas()),
        $source
    ));
}

I just know somehing is wrong in data conversation but I'm not familiar to PHP debugging and this is for experimental use, I appreciate if you could tell me what is wrong.


Solution

  • The $template argument of Mustache_Engine::render must be a string; however Mustache_Engine::loadTemplate returns an instance of the Mustache_Template class (which Mustache subsequently tries to treat as a string, which fails).

    You should be able to invoke the render(...) method on the template object instead (untested, though):

    $template = $mustache->loadTemplate(...);
    $renderedContent = $template->render($data);
    

    I'm not that familiar with Mustache, but according to the documentation, by default loadTemplate needs to be invoked with the template string, and not a template file name. Consider also configuring a FileSystemLoader for loading your templates:

    $mustache = new Mustache_Engine(array(
        'loader' => new Mustache_Loader_FilesystemLoader($pathToTemplateDir),
    ));