【问题标题】:Is it possible to let Mustache (php) partials contain their own data?是否可以让 Mustache (php) 部分包含自己的数据?
【发布时间】:2014-08-05 21:13:00
【问题描述】:

我想让 Mustache 模板引用一个局部,其中局部也将数据添加到上下文中。而不必将数据中的数据定义到初始的 Mustache 渲染中。

我在https://gist.github.com/lode/ecc27fe1ededc9b4a219 有一个模型

归结为:

<?php

// controller
$options = array(
    'partials' => array(
        'members_collection' => new members_collection
    )
);
$mustache = new Mustache_Engine($options);

$template = '
    <h1>The team</h1>
    {{> members_collection}}
';
echo $mustache->render($template);

// viewmodel
class members_collection {
    public $data;

    public function __toString() {
        $template = '
            <ul>
                {{# data}}
                    {{.}}
                {{/ data}}
            </ul>
        ';

        $mustache = new Mustache_Engine();
        return $mustache->render($template, $this);
    }

    public function __construct() {
        $this->data = array(
            'Foo Bar',
            'Bar Baz',
            'Baz Foo',
        );
    }
}

这会产生类似Cannot use object of type members_collection as array 的错误。

有没有办法让它工作?还是使用__toString 不是正确的方法?并且会使用 partials_loader 或 __invoke 帮助吗?我得到了它,但可能会错过一些东西。

【问题讨论】:

    标签: php viewmodel mustache.php


    【解决方案1】:

    在上面的示例中,members_collection 不是部分视图,而是子视图。两个非常小的更改使它起作用:在选项数组中,将partials 键更改为helpers;并且,在父模板中,从部分标记更改为未转义的插值标记({{&gt; members_collection}} -> {{{members_collection}}})。

    <?php
    
    require '/Users/justin/Projects/php/mustache/mustache.php/vendor/autoload.php';
    
    // controller
    $options = array(
        'helpers' => array(
            'members_collection' => new members_collection
        )
    );
    $mustache = new Mustache_Engine($options);
    
    $template = '
        <h1>The team</h1>
        {{{members_collection}}}
    ';
    echo $mustache->render($template);
    
    // viewmodel
    class members_collection {
        public $data;
    
        public function __toString() {
            $template = '
                <ul>
                    {{# data}}
                        {{.}}
                    {{/ data}}
                </ul>
            ';
    
            $mustache = new Mustache_Engine();
            return $mustache->render($template, $this);
        }
    
        public function __construct() {
            $this->data = array(
                'Foo Bar',
                'Bar Baz',
                'Baz Foo',
            );
        }
    }
    

    【讨论】:

      【解决方案2】:

      我假设你在 PHP 中使用 bobthecow PHP 实现 Mustache 模板。

      截至我上次检查时,Mustache PHP 不支持数据驱动的部分。您想要一种支持部分的“控制器”......但是,目前的部分只是简单的包含此文件样式的部分。

      您必须自己构建它。祝你好运!

      【讨论】:

        猜你喜欢
        • 2015-07-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-11
        • 1970-01-01
        • 1970-01-01
        • 2016-06-01
        相关资源
        最近更新 更多