After my last blog post, Consuming Services - How to get useful data into your app, a friend asked for advice on how to render the data that's returned to his app in a clean, simple way.
Immediately, two simple ways to accomplish this came to my mind. One using string concatenating and one using a hidden block of HTML as a template.
Let's take a closer look at the method of using string concatenation.
First, the UI:
This simple UI allows for the entry of a search term which will be searched for once the user clicks on the 'Search' button. The twitterSearchConcatenate function is called:
In this function a call is made to the Twitter search service and will concatenate together a simple display of each tweet that has been returned. Once we have the complete block of HTML we want we then create a list item object (li tag) and add the block of concatenated text in as the HTML content of this new item object and append it in to our existing unordered list. Yes, the location where the concatenation takes place could have been formatted differently to make it look better but I think anyone who looks at this will see, no matter how the code is formatted it, will always be difficult to support and maintain. A function that implements printf or String.Format() like functionality or better yet use the sprintf library could have made this look better as well. In the end, the HTML would be in you script and that just seams wrong no matter how good you make the code look.
Let’s look at a different way to go about this. First, we will add a div tag that we want and use its content as a template.
As you can see, nothing special here. The style is set to “display: none” so this html will not show up in our UI. With this template we can use some simple jQuery functions to find and clone this over and over for each item we get in our data.
Note: I am not including the UI HTML here as it’s extremely similar to what is above but you can see it in the complete project on GitHub.
The code is quite similar but this time the jQuery.clone and jQuery.find functions are used to accomplish what is needed. For each item in the returned search result the template HTML in the hidden div tag is cloned. In each clone we simply alter the appropriate property of the tag we want to display the data. The benefits are easy to see. With the HTML in the HTML editor it’s quite easy to modify the layout of the UI and the script is quite easy to read as well.
I hope this gives you some options regarding how you can simplify your rendered code.
The full project is available at https://github.com/woodyp/teplateResults-Demo
Subscribe to be the first to get our expert-written articles and tutorials for developers!