0

I've got this JSON:

{ 
status: "ok", 
posts: [ { 
          id: 1362, 
          type: "ser", 
          slug: "av-ss-xiii-3",

           fields: { 
                     price: [ "550" ], 
                     sale: [ "rent" ] 
            } 
       } ]
}

And I'm parsing it this way with mustache, but as you can see...fields is not an array of objects, it is an object with two attributes with array values...

{{#posts}}
<h1>{{type}}</h1>
        {{#fields}}
            <p> {{price}}:{{value}}</p>
         {{/fields}} 
{{/posts}}

I think I'll made a mistake during the parsing, cause it's no working for the price values.

2 Answers 2

2

Your template is close to working. The problem I can see is {{value}} expects a key in the fields object that is not present. Your template currently outputs the price with a colon and then nothing:

<h1>ser</h1>
<p> 550 :</p>

Perhaps you thought {{value}} would output 550, or you meant that to output the value of sale. In both cases it is a little odd to have the values wrapped in arrays: [ "550" ]. This doesn't matter though since there is only one element in each and this does not complicate your template at all. I can only guess at what your desired output is, but allow me to demonstrate your template in a working example.

{{#posts}}
    <h1>{{type}}</h1>
    {{#fields}}
    <p> {{price}} : {{sale}}</p>
    {{/fields}}
{{/posts}}

This will output the following HTML for your data:

<h1>ser</h1>
<p> 550 : rent</p>

Here is a jsFiddle to illustrate: template with multiple posts

I took the liberty of making up a second post object to demonstrate how your data might render with a collection. I also took a guess that you might mean to output both the price and the sale values.

I think you already understand this, but to be clear, {{#fields}} ... {{/fields}} works like a conditional since fields is an object and not an array. That's fine. In the case that fields is falsy (for example, undefined or false), your template won't render the p element.

Please note I used jQuery in the jsFiddle but only for convenience to access the template and DOM elements.

I hope that helps, but let me know if you have any questions. If that's not what you're looking for, please edit your question to describe your desired output.

Sign up to request clarification or add additional context in comments.

Comments

0

Finally I found it...it was a question of 'method', using .toHtml it gives nothing with arrays...using .render it works fine! Thanks

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.