Mustache JS Template with JSON Collection

后端 未结 3 1897
眼角桃花
眼角桃花 2020-12-21 15:43

Hi this is my first attempt to use MustacheJS with a JSON webservice in .net

Currently I am struggling I can\'t seem to find what I am doing wrong setting this basic

相关标签:
3条回答
  • 2020-12-21 16:26

    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 "/".

    0 讨论(0)
  • 2020-12-21 16:33

    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/

    0 讨论(0)
  • 2020-12-21 16:48

    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/

    0 讨论(0)
提交回复
热议问题