Lukas
Lukas

Reputation: 7744

Use single variable to define mustache tag

Is there any option to set mustache tag with some define variables? Something like this:

Json

{
    "color_set_01": [
        "white", "black"
        ],
    "color_set_02": [
        "green", "red"
    ]
}

JavaScript

var color = 'color_set_' + options.number;

$.getJSON('json/data.json', function(data) {
    var template = "<ul>{{color}}<li class="{{.}}"></li>{{/color}}</ul>";
    var html = Mustache.to_html(template, data);
    colors_panel.html(html);
});

and desired result if it's color_set_01 aray

<div class="colors_panel">
    <ul>
      <li class="white">
      <li class="black">
    </ul>
</div>

Upvotes: 1

Views: 792

Answers (1)

Smern
Smern

Reputation: 19086

Okay, after a quick look at http://coenraets.org/blog/2011/12/tutorial-html-templates-with-mustache-js/, I think this would work:

var template = "<ul>{{#"+color+"}}<li class=\"{{.}}\"></li>{{/"+color+"}}</ul>";

It seems that the # sets up the ability to use a list, the . is basically each item of the list. Also, you needed to escape your quotes in the template string.

This also assumes your JSON should look like this:

{
    "color_set_01": [
        "white", "black"
    ],
    "color_set_02": [
        "green", "yellow"
    ]
}

If there are more than color_sets in your JSON, then you'll have to show what the parents of color_set_01 is up until the top for me to help further.

Upvotes: 1

Related Questions