Search code examples
javascripttemplateshandlebars.jsmustache

Mustache.js: large JSON dictionary & smaller know list of entries to display randomly onfly?


I just started to use mustache.js, I have my json dictionary, my html template, and my mustache.js startup code to inject the whole. My html-mustache template is such:

<script id="tpl" type="text/html">
    <div class="body">
        <p>{{口.zht}}</p>
        <p>{{口.sam.pyn}}</p>
        <p>{{口.sam.fra}}</p>
    </div>
</script>

In my test case with a given existing entry '口', it works (1). But I notice that Mustache seems designed to iterate all the JSON entries. However, I want to work on a small focusList of entries

var focusList = ['們','火山口','火'];

for which I want to pick the corresponding data from my larger (~1000 entries) JSON dictionary.

How can I change or make variable {{#口}} and {{/口}} according to my focusList, so I may print my template with the correct data?

Is there some kinds of variables in the template such:

<script id="tpl" type="text/html">
    <div class="body">
        <p>{{{{entry}}.zht}}</p>
        <p>{{{{entry}}.sam.pyn}}</p>
        <p>{{{{entry}}.sam.fra}}</p>
    </div>
</script>

and in the JS I add:

var entry = focusList[Math.floor(Math.random() * focusList.length)]]

?


Solution

  • Solution: given a small list of keys, mustache-print relevant entries from larger JSON data:

    //1. Suggest a smaller custom list of keys existing in the larger data. 2. Randomize.
    var focusList = ['們','火山口','火'];
    var randomKey = focusList[Math.floor(Math.random() * focusList.length)];
    //3. variable + Template + variable. 4. printing.
    var template = ('{{#'+ randomKey +'}}'+ $('#tpl').html() +'{{/'+randomKey+'}}'); // as {{#火}} ... {{/火}}
    var output = Mustache.render(template, myBigJSON);
    $('#main').append(output)
    

    Alternatively 1: you can also get the whole list of entries using Object.keys (2) to print a random entry from the WHOLE list:

    //1. Get and create the list of all keys
    var focusList = Object.keys(myBigJSON);
    

    Last, rather than randomize and loop which may repeat some entries, you may shuffle the given list and iterate the shuffled list systematically to print each item systematically.