【问题标题】:Access to a callback's method from Mustache从 Mustache 访问回调的方法
【发布时间】: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


    【解决方案1】:

    简短的回答是,如果您传递值而不是让模板调用来获取它们,Mustache 会更好地工作:)

    $m->render($tpl, ['Post' => Post::getObject()]);
    

    如果您对更长的答案感兴趣:

    Helper 只是渲染上下文中的奖励值。所以添加你的 Post 助手相当于用['Post' =&gt; ['Post', 'getObject']]调用render()。

    在 Mustache 中,如果标签的 value 是一个函数,它会以特殊方式处理(它们被称为 lambdas)。您可以查看示例on the Mustache.php wiki

    所以在你的情况下,你遇到了这种区别。基本上,您的渲染调用中的{{Post}} 的值不是一个新帖子,它是可调用的['Post', 'getObject']。所以该值触发了 lambda 逻辑,而不是正常的字符串插值。

    【讨论】:

    • 感谢贾斯汀的上述回答,以及您出色的 Mustache 实施。由于我们特殊的架构、原则和限制,我们不能向 Mustache 添加对象或 lambda,数组回调是我们唯一的选择。因此,我们将决定要么分叉 Mustache,要么实现我们自己的满足我们需求的模板引擎。再次感谢您出色的 Mustache 实施;{
    猜你喜欢
    • 2020-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    • 1970-01-01
    • 2021-06-07
    相关资源
    最近更新 更多