premasagar / tim

A tiny, secure JavaScript micro-templating script.
251 stars 26 forks source link

Nested List #18

Closed tomalex0 closed 9 years ago

tomalex0 commented 9 years ago

I'm trying to render nested json to created nested list. is there a simple way to do this?

If you can share an example it will be helpful.

<ul>
  <li>
     <h2>One</h2>
     <ul>
        <li>One 1</li>
         <li>One 2</li>
     </ul>
  </li>
  <li>
     <h2>Two</h2>
     <ul>
        <li>Two 1</li>
         <li>Two2</li>
     </ul>
  </li>
</ul>
[
    {
        "name": "One",
        "items": [
            {
                "itemname": "One 1"
            },
            {
                "itemname": "One 2"
            }
        ]
    },
    {
        "name": "Two",
        "items": [
            {
                "itemname": "Two 1"
            },
            {
                "itemname": "Two 2"
            }
        ]
    }
]
tomalex0 commented 9 years ago

I figured out a way as specified below

var listitems = [
    {
        "name": "One",
        "items": [
            {
                "itemname": "One 1"
            },
            {
                "itemname": "One 2"
            }
        ]
    },
    {
        "name": "Two",
        "items": [
            {
                "itemname": "Two 1"
            },
            {
                "itemname": "Two 2"
            }
        ]
    }
];
var myList = "";
var listitem = '<li><a href="#">{{itemname}}</a></li>';
var mainNav = '<li> <h2 >{{name}}</h2> <ul> {{listitem}} </ul> </li>';

for (i=0; i<(listitems.length); i++){
   var itemchilds = listitems[i].items;
   var myListItem = "";
   for (j=0;j<(itemchilds.length);j++){
        myListItem += tim(listitem, {itemname: itemchilds[j].itemname});
   }
   myList += tim(mainNav, {name: listitems[i].name,listitem : myListItem});
}