使用不同的数据多次渲染一个小胡子 [英] Rendering one mustache partial multiple times with different data

查看:53
本文介绍了使用不同的数据多次渲染一个小胡子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个要并排渲染的对象.在任何情况下,我永远都不会想渲染更多或少于两个.我的模型设置如下:

I have two objects that I want to render side by side. There is never a case where I will want to render more, or less than two. My model is setup like so:

{
  obj1: {...},
  obj2: {...}
}

使用胡子模板,我想使用相同的局部对象渲染每个对象:

Using mustache templates, I want to render each object using the same partial:

<div>
  <h1>Object 1</h1>
  {{>objPartial}}
</div>
<div>
  <h1>Object 2</h1>
  {{>objPartial}}
</div>

但是,胡子似乎不支持将上下文传递给局部对象.似乎应该支持执行{{>objPartial obj1}}之类的操作,但是我找不到任何有关设置局部上下文的文档.

However, mustache doesn't seem to support passing a context to the partial. Doing something like {{>objPartial obj1}} seems like it should be supported, but I can't find any documentation on setting a context for a partial.

是否支持这种事情?如果没有,如何在不复制部分(objPartial1objPartial2)的情况下实现相同的效果?

Is this sort of thing supported? If not, how can I accomplish the same effect without duplicating the partial (objPartial1 and objPartial2)?

推荐答案

我认为您正在寻找的语法不是{{>objPartial obj1}},而是应该的

The syntax I think you are looking for is not {{>objPartial obj1}}, but rather it should be

{{#obj1}}
{{>objPartial}}
{{/obj1}}

{{#}}的语法不仅适用于数组-对于非数组对象,该对象也成为当前作用域的一部分.

The syntax for {{#}} isn't only for arrays - for non array objects the object becomes part of the current scope.

我已经分叉了maxbeatty的示例,并对其进行了修改以显示此语法:

I've forked maxbeatty's example and modified it to show this syntax:

<script type="template/text" id="partial">
    <ul>
        {{#name}}
        <li>{{.}}</li>
        {{/name}}
    </ul>
</script>

<script type="template/text" id="main">
    <div>
        <h1>Stooges</h1>
        {{#object1}}
        {{>objPartial}}
        {{/object1}}
    </div>
    <div>
        <h1>Musketeers</h1>
        {{#object2}}
        {{>objPartial}}
        {{/object2}}
    </div>
</script>​

<script type="text/javascript">    
    var partial = $('#partial').html(),
        main = $('#main').html(),
        data = {

            object1: {
                name: ["Curly", "Moe", "Larry"]},
            object2: {
                name: ["Athos", "Porthos", "Aramis", "D'Artagnan"]}

        },
        html = Mustache.to_html(main,data, {
            "objPartial": partial
        });
    document.write(html);
</script>

链接到jsfiddle: http://jsfiddle.net/YW5zF/3/

Link to jsfiddle: http://jsfiddle.net/YW5zF/3/

这篇关于使用不同的数据多次渲染一个小胡子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆