1

I'm new to JSON and mustache. I'm trying to iterate an array that I've created using Mustache and I'm running into some issues. My code looks like this:

var shows=[         
        {"title":"Strawberry Shortcake","description":"A show about a cake","video":"none","category":"chilren"},
        {"title":"Vanilla Ice","description":"A show about a ice","video":"none","category":"adult"}
];

var template="{{#shows}}{{.}}{{/shows}}";

var html=Mustache.render(template,shows);

document.write(html);
2
  • 1
    Please explain those issues. And what do you expect. Commented Feb 28, 2012 at 16:10
  • You've written "interate" instead of "iterate". I can't edit it myself since it's just one character. Commented Feb 28, 2012 at 16:12

2 Answers 2

2

You want "shows" to be in a hash in order to properly iterate:

var shows={"shows":[        
        {"title":"Strawberry Shortcake","description":"A show about a cake","video":"none","category":"chilren"},
        {"title":"Vanilla Ice","description":"A show about a ice","video":"none","category":"adult"}
]};

var template="{{#shows}}{{.}}{{/shows}}";

var html=Mustache.render(template,shows);

document.write(html);

This will have the desired effect of producing your template multiple times.

UPDATE

To your question on Lambdas. I just looked this up in the manual. I think it covers what you were asking about:

When the value is a callable object, such as a function or lambda, the object will be invoked and passed the block of text. The text passed is the literal block, unrendered. {{tags}} will not have been expanded - the lambda should do that on its own. In this way you can implement filters or caching.

Template:

{{#wrapped}}
  {{name}} is awesome.
{{/wrapped}}

Hash:

{
  "name": "Willy",
  "wrapped": function() {
    return function(text) {
      return "<b>" + render(text) + "</b>"
    }
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Followup question. Is there a way that Mustache natively supports the ability to filter results. For example I only want to display shows where the category value is adult?
1

u can do like this:

var shows=[        
        {"title":"Strawberry Shortcake","description":"A show about a cake","video":"none","category":"chilren"},
        {"title":"Vanilla Ice","description":"A show about a ice","video":"none","category":"adult"}
];

var template="{{#.}}title:{{title}},video:{{video}}{{/.}}";

var html=Mustache.render(template,shows);

document.write(html);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.