Mustache JS Template with JSON Collection

不羁岁月 提交于 2019-11-29 16:38:27
marty

Per @stealth on this question Mustache.js: Iterate over a list received via json

    {{ #. }}
        <b>{{Name}}</b>
    {{ /. }}

Note the only difference from @stealth's answer is a "#" instead of "/".

The line data = { 'roles': data }; is the most crucial. Its attaching the key to the data returned by web api or any other source of data like pagemethods or web service

$.ajax({
        dataType: "json",
        url: '/api/TestApi/GetAllRole',
        success: function (data) {          
            data = { 'roles': data }; // formatting the data to support the mustache    format  
            var html = Mustache.to_html($('#RoleTemplate').html(), data);
            $('#tblRole').append(html);

        }
    });

Few of my articles on the MustacheJs can be found here

INLINE FILTER FOR BASIC GRID USING MUSTACHEJS http://www.techguides.in/add-inline-filter-to-basic-grid-using-mustache/

Master Details Grid on Demand data loading : Using Mustache.JS http://www.techguides.in/master-details-grid-on-demand-data-loading-using-mustache-js/

Sorting a Grid using MustacheJs http://www.techguides.in/enable-sorting-in-a-grid-bound-using-mustache-js/

short answer: YES

long answer: for security reasons [1], you need to wrap your JSON aray in an object anyways. for Mustache or any other library to be able to access your array you need to have at least one parent key on which you can base your iterator.
The "repo" key on your sample is the helper you need to tell mustache "go and iterate on the array that is inside the repo key", otherwise you have no way to tell the template what you want to output where

[1] this is just one of many resources you can find about why you need to wrap your JSON response in an object http://incompleteness.me/blog/2007/03/05/json-is-not-as-safe-as-people-think-it-is/

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