首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >带有JSON数据的Mustache.php抛出可捕获的致命错误

带有JSON数据的Mustache.php抛出可捕获的致命错误
EN

Stack Overflow用户
提问于 2015-11-27 18:35:16
回答 2查看 826关注 0票数 3

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

PHP脚本:

代码语言:javascript
复制
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数据:

代码语言:javascript
复制
{

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

}

胡子模板:

代码语言:javascript
复制
{{{# persons }}}
{{{# person }}}
<ul>
    <li>Name: {{name}}</li>
    <li>Number: {{number}}</li>
</ul>
{{{# person }}}
{{{/ persons }}}

但是PHP抛出了这个错误:

代码语言:javascript
复制
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

这就是points错误的来源(在上面的Engine.php文件中):

代码语言:javascript
复制
/**
 * 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调试,这是实验用的,如果你能告诉我出了什么问题,我很感激。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-11-27 19:17:55

$template参数的Mustache_Engine::render必须是一个字符串;但是,Mustache_Engine::loadTemplate返回Mustache_Template类的一个实例(随后,穆斯塔赫试图将该实例作为字符串处理,但失败)。

您应该能够在模板对象上调用render(...)方法(不过还没有测试):

代码语言:javascript
复制
$template = $mustache->loadTemplate(...);
$renderedContent = $template->render($data);

我不太熟悉小胡子,但是默认情况下,根据文件需要用模板字符串而不是模板文件名来调用loadTemplate。还请考虑配置用于加载模板的FileSystemLoader:

代码语言:javascript
复制
$mustache = new Mustache_Engine(array(
    'loader' => new Mustache_Loader_FilesystemLoader($pathToTemplateDir),
));
票数 2
EN

Stack Overflow用户

发布于 2015-11-27 20:10:56

我认为这是个错误:

代码语言:javascript
复制
{{{# person }}}
{{{/ persons }}}

尝试:

代码语言:javascript
复制
{{{#persons}}}
{{{#person}}}
<ul>
    <li>Name: {{name}}</li>
    <li>Number: {{number}}</li>
</ul>
{{{/person}}}
{{{/persons}}}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33963119

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档