php - 带有 JSON 数据的 Mustache.php 抛出可捕获的 fatal error

标签 php json template-engine mustache.php

我发现您可以将 JSON 文件转换为 PHP 数组和对象,并将该输出用作 Mustache.php 模板引擎的数据,如下例所示:

PHP 脚本:

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 数据:

{

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

}

mustache 模板:

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

但是 PHP 抛出这个错误:

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

这就是 PHP 指出错误的来源(上面错误中的 Inside Engine.php 文件):

/**
 * 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
    ));
}

我只知道数据对话有问题,但我对 PHP 调试不熟悉,这是用于实验用途,如果你能告诉我哪里出了问题,我将不胜感激。

最佳答案

Mustache_Engine::render$template 参数必须是一个字符串;但是 Mustache_Engine::loadTemplate 返回 Mustache_Template 类的实例(Mustache 随后尝试将其视为字符串,但失败了)。

您应该能够在模板对象上调用 render(...) 方法(尽管未经测试):

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

我对 Mustache 不太熟悉,但是 according to the documentation ,默认情况下 loadTemplate 需要使用模板字符串调用,而不是模板文件名。还可以考虑配置一个 FileSystemLoader 来加载您的模板:

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

关于php - 带有 JSON 数据的 Mustache.php 抛出可捕获的 fatal error ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33963119/

相关文章:

php - 让所有表单验证错误都显示在 symfony 的顶部?

javascript - 如何根据输入字段中的给定数据计算年龄?

javascript - AJAX 成功不触发

java - 非servlet JSP

php - PDO 连接截断的用户名

php - 在 PHP 中散列 JSON 不会产生与在 Javascript 中针对 unicode 字符相同的结果

java - 如何通过修改结构来反序列化Json?

javascript - 将 google 脚本对象传递给 html 模板

php 爆炸在 javascript 模板中不起作用

php - 如何安装扩展/