0

I have a json with the following format. I want to fill that json in view using mustache js.

Json Format

Image

Code for rendering json is

render: function () {
    var tmplData = self.jsonArrayFull;
    var out = Mustache.render(self._dashboardTemplate(), tmplData);
    self.element.html(out);
}

_dashboardTemplate: function () {
            var template = '<div id="layoutContainer" style="background-color:{{backgroundColor}}"></div>';
            return template;
        },

How can I do this? Its rendering null. Please help..

Nithin Viswanathan
  • 3,245
  • 7
  • 39
  • 84

1 Answers1

1

Your problem comes from the fact that tmplData is an array, not an object, so when your template looks for {{backgroundColor}}, that is a backgroundColor of array, which doesn't exist.

To solve this, either pick the first item in the array to pass to Mustache.render ie:

Mustache.render(self._dashboardTemplate(), tmplData[0])

Or put a loop into your template to render each array item like:

var template = '{{#.}}<div id="layoutContainer" style="background-color:{{backgroundColor}}"></div>{{/.}}';

See this question: Can mustache iterate a top-level array? for details about rendering a top level array.

Community
  • 1
  • 1
Ian Routledge
  • 4,012
  • 1
  • 23
  • 28
  • @lanRoutledge If i want another item from that array. What can i do for that? for example, Now there is only background color, but i need the dashlet items also.. – Nithin Viswanathan Jul 16 '14 at 09:22
  • Dashlets is not another item in the array, it is a property of an object in that array. You could do something like: `var template = '{{#.}}
    {{#dashlets}}
    {{.}}
    {{/dashlets}}
    {{/.}}';`(not tested)
    – Ian Routledge Jul 16 '14 at 10:20