我发现您可以将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
}
}]
}胡子模板:
{{{# 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这就是points错误的来源(在上面的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调试,这是实验用的,如果你能告诉我出了什么问题,我很感激。
发布于 2015-11-27 19:17:55
$template参数的Mustache_Engine::render必须是一个字符串;但是,Mustache_Engine::loadTemplate返回Mustache_Template类的一个实例(随后,穆斯塔赫试图将该实例作为字符串处理,但失败)。
您应该能够在模板对象上调用render(...)方法(不过还没有测试):
$template = $mustache->loadTemplate(...);
$renderedContent = $template->render($data);我不太熟悉小胡子,但是默认情况下,根据文件需要用模板字符串而不是模板文件名来调用loadTemplate。还请考虑配置用于加载模板的FileSystemLoader:
$mustache = new Mustache_Engine(array(
'loader' => new Mustache_Loader_FilesystemLoader($pathToTemplateDir),
));发布于 2015-11-27 20:10:56
我认为这是个错误:
{{{# person }}}
{{{/ persons }}}尝试:
{{{#persons}}}
{{{#person}}}
<ul>
<li>Name: {{name}}</li>
<li>Number: {{number}}</li>
</ul>
{{{/person}}}
{{{/persons}}}https://stackoverflow.com/questions/33963119
复制相似问题