Вопрос

im having a problem with underscore templating but i can't just find the way to solve my problem, my case is as follows. I have a json object returned from a web service that looks something like this:

json= [{"username":"blue", "user_id":"1", "group_id":"1" ...},
       ...,{"username":"teal", "user_id":"1", "group_id":"2" ...}]

After getting this object back from the server i'm trying to make it so that i can use a template to render the object on a webpage, to do so i did "groupby" the array on a fashion that i though would suit my needs the best by doing the following:

json = _.chain(json).sortBy("user_id").groupBy("user_id").value();

This returned an object with the following structure:

json= {"1":[{"username":"blue", "user_id":1, ...},
       ...,{"username":"teal", "user_id":1, ...}],"228":[{...},{...}]}

Now, what i wanted was to use the following template:

<script type="text/template" class="template-users">
            <div class="accordion">
                {%- _.each( rc, function( rc ){ %}

                <h3>

                    {%- rc.user_id%}

                </h3>
                <div>
                    <div>
                        <a class="group{%- rc.group_id%}" id="{%- rc.group%}">
                            <p>{%- rc.group %}</p>
                            <p>(group{%- rc.group%})</p>
                        </a>
                    </div>
                </div>
                {%- }); %}
            </div>


        </script>

I set the template variable inside my js file like so:

_.templateSettings.variable = "rc";

I've also changed the following lines inside the underscore.js min file 'cause i'm using asp.net

_.templateSettings = {interpolate : /\{\{(.+?)\}\}/g,      
                      evaluate    : /\{%([\s\S]+?)%\}/g,  
                      escape      : /\{%-([\s\S]+?)%\}/g};

Still, whenever i tried to run this, it wont 'cause the template its full of empty stuff (thats to say every value i have inside the "{%- %}" is returning nulls or emptys, but i know for a fact that the json is being populated before using it on the template by doing the following:

var template = _.template(
                        $("script.template-users").html()
                    );

i have seen somewhere somewhere that they use _.each( rc.listItems, function( listItem ){}); to iterate over the items on the object, but thats only because they have an object with the following structure:

var templateData = { listTitle: "Olympic Volleyball Players", listItems: [ { name: "Misty May-Treanor", hasOlympicGold: true }, { name: "Kerri Walsh Jennings", hasOlympicGold: true }, { name: "Jennifer Kessy", hasOlympicGold: false }, { name: "April Ross", hasOlympicGold: false } ] };

So the question is, who can i make my code work ? or if not possible, who can i make it so my json object is arranged on the same fashion as the one described above ?

Thanks in advance.

Это было полезно?

Решение

Here's a fiddle with a working example: http://jsfiddle.net/uBaZ6/1/

_.templateSettings = {interpolate : /\{\{(.+?)\}\}/g,      
                  evaluate    : /\{%([\s\S]+?)%\}/g,  
                  escape      : /\{%-([\s\S]+?)%\}/g};
var data = [{"username":"blue", "user_id":"1", "group_id":"1"},{"username":"teal", "user_id":"2", "group_id":"2"},{"username":"red", "user_id":"3", "group_id":"2"},{"username":"blue", "user_id":"1", "group_id":"1"}];

var dataSorted = _(data).chain().groupBy("user_id").sortBy("group_id").value();
var userTemplate = _.template($("script.template-users").html());

$("#acc").html(userTemplate({'groups':dataSorted}));

The key thing is that you need a named key for the template to get something to hold onto. Otherwise, it takes your array and just fills it into the global namespace, which in this case doesn't make sense because it's an array. So to fix that, just convert it into an object before you send it into your template. So for our first pass we map your data to groups

userTemplate({'groups':dataSorted})

and then we use it in the template like

{% _.each(groups, function(group){ %}
<h3>{%- group[0].group_id %}</h3>

You can see http://underscorejs.org/#template for more about Underscore templates. I think the developers don't really look at the US Templates as being very robust (or at least that's the way it used to be)

Другие советы

Will beat me to the punch, but I thought I'll share my jsFiddle anyway.

http://jsfiddle.net/RXCrr/1/

     <script type="text/template" class="template-users">
        <div class="accordion">
            <% _.each( json, function( rc ) { %>
                <%=_.template($(".template-user").html(), rc) %>
            <% }); %>
        </div>
    </script>

    <script type="text/template" class="template-user">
        <h3>
            <%= user_id%>
        </h3>
        <div>
            <div>
                <a class="group<%= group_id%>" id="<%= group_id%>">
                    <p><%= group_id %></p>
                    <p>(group<%= group_id%>)</p>
                </a>
            </div>
        </div>
    </script>
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top