Question

How can I loop a nested json like this below with jsrender/ jsviews?

var data = {  
    nested: {
        page: {
            type: "X",
            items: {
                "0":{"title":"page - hello"},
                "1":{"title":"page - world"}
            }
        },
        post: {
            type: "Y",
            items: {
                "0":{"title":"post - hello"},
                "1":{"title":"post - world"}
            }
        }  
    }

};

template,

{{for nested}}
<div>
    <h1>Type: {{ :type }}</h1>
    {{for items}}
    <p>Title:  {{:title}} </p> 
    {{/for}}
</div>
{{/for}}

result,

Type: {{ :type }}

What I am after,

Type: X
Title - page - hello
Title - page - World

Type: Y
Title: post - hello
Title: post - World
Was it helpful?

Solution

Updated response:

JsRender and JsViews have a {{props}} tag for iterating through fields, which is documented here.

For the example data and output requested above, you can do it using the following template:

<script id="myTmpl" type="text/x-jsrender">

{{props nested}}
  <div>
    <h1>Type: {{:prop.type}}</h1>
    {{props prop.items}}
      <p>Title: {{:prop.title}}</p>
    {{/props}}
  </div>
{{/props}}

</script>

And the following code:

var myTmpl = $.templates("#myTmpl");

var data = {  
  nested: {
    page: {
      type: "X",
      items: {
        "0":{"title":"page - hello"},
        "1":{"title":"page - world"}
      }
    },
    post: {
      type: "Y",
      items: {
          "0":{"title":"post - hello"},
          "1":{"title":"post - world"}
      }
    }
  }
};

var html = myTmpl.render(data);

Here it is in a jsfiddle

OTHER TIPS

I think that the problem your having is your declaring an object instead of an array in your data. Try it with the data bellow.

  var data = {  
      nested: {
        {
            type: "X",
            items: {
                "0":{"title":"page - hello"},
                "1":{"title":"page - world"}
            }
        },
        {
            type: "Y",
            items: {
                "0":{"title":"post - hello"},
                "1":{"title":"post - world"}
            }
        }  
    }

  };

This way nested is an array and the for should be able to loop over it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top