Rendering one mustache partial multiple times with different data

拈花ヽ惹草 提交于 2019-12-03 07:45:22
Doug Fish

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.

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>

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

You could adjust your model to include the h1 and div so you could loop over a list sending different data to objPartial each time

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

<script type="template/text" id="main">
    {{#section}}
    <div>
        <h1>{{title}}</h1>
        {{>objPartial}}
    </div>
    {{/section}}
</script>

<script type="text/javascript">
var partial = $('#partial').html(),
    main = $('#main').html(),
    data = {
        section: [
            {
            title: "Object 1",
            name: ["Curly", "Moe", "Larry"]},
        {
            title: "Object 2",
            name: ["Athos", "Porthos", "Aramis", "D'Artagnan"]}
        ]
    },
    html = Mustache.to_html(main,data, {
        "objPartial": partial
    });
document.write(html);
</script>

See it on jsFiddle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!