Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mustache looping error when trying to display data

I am having a problem doing a loop in mustache. Basically a usr has the ability to add options to products. Each option can have more then 1 choice. Also they come together Choice Name + Price. I get the following error:

Uncaught Error: Unopened section: choices

My code:

var choices = new Object();

    $("[name='choice_name']").each(function(){
        var c_name = $(this).val();
        $("[name='choice_price']").each(function(){
            var c_price = $(this).val();
            choices.choice_name = c_name;
            choices.choice_price = c_price;
        });
    });

    console.log(choices);

    var templateData = {
        name: $("[name='option_name']").val(),
        type: $("[name='option_type']").find("option:selected").val(),
        choices: choices
    };

    $.get(default_url+"js_temp/options_widget.html", function(templates){
        $('.current_options').append(Mustache.render(templates, templateData));
    });

HTML:

<div>
  <p class="pull-right"><i class="icon icon-pencil"></i><br /><i class="icon icon-trash"></i></p>
    <p><strong>Option Name:</strong> {{option_name}}</p>
    <p><strong>Option Type:</strong> {{option_type}}</p>
    <hr>
    {{choices}}
    <div class="row-fluid">
      <div class="span7"><p><strong>Choice Name:</strong> {{choice_name}}</p></div>
      <div class="span5"><p><strong>Price:</strong> {{choice_price}}</p></div>
    </div>
    {{/choices}}
</div>

I think I can't achieve the correct format for the choices object. What am I doing wrong?

Thank you.

like image 797
user1701398 Avatar asked Dec 02 '12 23:12

user1701398


1 Answers

The syntax for a loop is {{#choices}} {{prop}} {{/choices}} -- looks like you are missing the #.

{{#choices}}
    <div class="row-fluid">
      <div class="span7"><p><strong>Choice Name:</strong> {{choice_name}}</p></div>
      <div class="span5"><p><strong>Price:</strong> {{choice_price}}</p></div>
    </div>
{{/choices}}

Also, in constructing choices, you're overwriting each object -- I think you want to push each one to the array. Try this:

var choices = [];

$("[name='choice_name']").each(function(){
    var c_name = $(this).val();
    $("[name='choice_price']").each(function(){
        var c_price = $(this).val();
        choices.push({ 
            choice_name: c_name, 
            choice_price: c_price 
        });
    });
});

See here: http://jsfiddle.net/U6pLT/1/

like image 136
McGarnagle Avatar answered Oct 14 '22 22:10

McGarnagle