【发布时间】:2015-08-09 12:23:48
【问题描述】:
谁能解释一下如何创建对象并从 Mustache 模板调用它的方法?
我想为 Mustache 添加一些回调作为助手:
$options['helpers'] = array(
'Post' => array('\Classes\Post', 'getObject')
);
这是一个示例类:
namespace Classes;
class Post
{
public static function getObject()
{
return new Post(\Request::postId());
}
public function post()
{
$post = new \stdClass;
$post->title = 'Title';
$post->content = 'Content';
return $post;
}
public function comments()
{
$comment = new \ArrayObject();
$comment[0] = new stdClass;
$comment[0]->name = 'David';
$comment[0]->content = 'I\'m David';
$comment[1] = new stdClass;
$comment[1]->name = 'Mary';
$comment[1]->content = 'I\'m Mary';
$comment[2] = new stdClass;
$comment[2]->name = 'Sana';
$comment[2]->content = 'I\'m Sana';
return $post;
}
}
并在 post.Mustache 文件中使用它:
<h1>{{Post.title}}</h1>
<p>{{Post.content}}</p>
<hr>
{{#Post.comments}}
<b>{{name}}</b> Said: {{content}}<br><br>
{{/Post.comments}}
但是,这似乎不是访问链式方法和属性的正确方法?!
【问题讨论】:
标签: php oop callback mustache template-engine