I have the following line in my script, building a string based on news feed data retrieved from JSON:
var buildstring = "<table><tr><img src=" + obj.value.items[x]["media:content"].url + "> <b>" + obj.value.items[x].title + "</b><br /><td>" + obj.value.items[x].description.content + "</td></tr></table><br />";
In general it works fine – except for one thing. The feed that is being parsed occasionally doesn’t have an image file associated with a particular title and description, and in that case, the entire script fails.
Is there any way to get the script to skip over any missing item in the feed and to build the string from the items that are there? E.g. if there is no image file for a story, the string consists of just the title and description? In the typical case I am taking 5 – 10 stories – if all of them have the 3 elements (image, title and description.content), it’s all fine. If one story is missing the image file, I get nothing at all.
Thanks for any advice or assistance.
EDIT:
More complete code:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.1.min.js"> </script><script type="text/javascript">
function pipeCallback(obj) {
document.write("<div id=testdiv><b>LATEST NEWS</b><hr>");
var x;
for (x = 0; x < obj.count ; x++)
{
var imageurl = obj.value.items[x]["media:content"].url ? obj.value.items[x]["media:content"].url : "http://static.jquery.com/org/images/project/jquery-project-sm.png";
var buildstring = "<table><tr><img src=" + imageurl + "> <b>" + obj.value.items[x].title + "</b><br /><td>" + obj.value.items[x].description.content + "</td></tr></table><br />";
document.write(buildstring);
buildstring = null;
}
document.write("</div>");
}
</script>
You could use a ternary expression to build the string:
Obviously this gets really ugly, fast, which is why they invented client-side templating (JQuery templating, Underscore.js, Mustache.js, Handlebars.js, etc, take your pick).
These allow you to separate the data from the markup, so you can write something like this:
And you can get the HTML by from the data + template: