Beginner here trying to figure out best way to structure some JSON and output the below nested <ul>
Each of the bolded items below are the values in the JSON. How might I structure the JSON and then how to build the DOM structure with jQuery? Any help greatly appreciated.
<ul>
<li>Topic 1
<ul>
<li id="foo_item1a">
<a href="destination_Item1a">
<strong>Lorem</strong>
<span>Item 1a</span>
<em>Ipsum</em>
</a>
</li>
<li id="foo_item1b">
<a href="destination_Item1b">
<strong>Dolor</strong>
<span>Item 1b</span>
<em>Sit</em>
</a>
</li>
</ul>
</li>
<li>Topic 2
<ul>
<li id="foo_item2a">
<a href="destination_Item2a">
<strong>Lorem</strong>
<span>Item 2a</span>
<em>Ipsum</em>
</a>
</li>
<li id="foo_item2b">
<a href="destination_Item2b">
<strong>Dolor</strong>
<span>Item 2b</span>
<em>Sit</em>
</a>
</li>
</ul>
</li>
</ul>
I have become a big fan of mustache.js recently for doing exactly this kind of thing.
http://github.com/janl/mustache.js/
Edit:
if I tweak calvinf's JSON format a little then this is an example using mustache.js:
<html>
<head>
<script type="text/javascript" src=" http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://github.com/janl/mustache.js/raw/master/mustache.js"></script>
<script type="text/javascript">
var topics = {
topics: [
{
title : "Topic 1",
items : [
{title: "1a", link: "http://www.example.com/", text: "Link Text or HTML"},
{title: "1b", link: "http://www.example.com/", text: "Link Text or HTML"}
]
},
{
title : "Topic 2",
items : [
{title: "2a", link: "http://www.example.com/", text: "Link Text or HTML"},
{title: "2b", link: "http://www.example.com/", text: "Link Text or HTML"}
]
}
]};
var template = "<ul>{{#topics}}<li>{{title}}<ul>{{#items}}<li id=\"foo_item{{title}}\"><a href=\"{{link}}\">{{text}}</a></li>{{/items}}</ul>{{/topics}}</ul>";
$(document).ready(function() {
$("#topics").html(Mustache.to_html(template, topics));
});
</script>
<title></title>
</head>
<body>
<div id="topics"></div>
</body>
</html>
If you want a speed benchmark for JavaScript templating libraries I found this link useful:
http://www.viget.com/extend/benchmarking-javascript-templating-libraries/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With