【问题标题】:How to pass data from different sources using mustache.php and mustache partials?如何使用 mustache.php 和 mustache partials 传递来自不同来源的数据?
【发布时间】:2014-09-10 10:31:43
【问题描述】:

我正在使用mustache.php。 假设我的 mustache 模板中有如下 HTML 结构(只是一个示例,让您了解我的问题):

<nav>
    <div>
        <div>
            <a>{{object1.title}}</a>
        </div>
        <menu>
            {{#object2.items}}
                <li><a>{{title}}</a></li>
            {{/object2.items}}
        </menu>
    </div>
</nav>

我的问题是模板应该使用的数据来自两个不同的来源(object1 和 object2)。

根据mustache.php wiki,我可以像这样加载模板:

<?php

$object1 = some_function_returns_a_json_object( 1 );

$mustache = new Mustache_Engine();
$my_template = $mustache->loadTemplate( 'my_template' ); // will fetch my_template.mustache
echo $my_template->render( $object1 ); // passes data from $object1 to my_template.mustache

但是我在上面的 html 示例中的菜单项怎么样?它们需要来自另一个我不能在同一个 $object1 中拥有的对象。

我不明白如何处理一个模板(和部分)和来自多个来源的数据。

我应该将上面的 HTML 拆分成不同的部分吗?即便如此,我如何将 json 数据传递给嵌套的部分?

【问题讨论】:

    标签: php template-engine mustache partials mustache.php


    【解决方案1】:

    哦,刚刚想通了

    我可以在这里将我的对象作为数组传递

    echo $my_template->render( array( 'object1' => $object1, 'object2' => $object2 ) );
    

    它会起作用 - 在 mustache.php 文档中并不太清楚

    不确定这是否是最佳做法,但看起来也适合在局部中使用

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-09
      • 2018-11-11
      • 2023-03-22
      • 1970-01-01
      • 2020-09-25
      • 2018-05-30
      • 2011-09-22
      • 1970-01-01
      相关资源
      最近更新 更多