Now that jQuery templates are becoming popular, many ASP.NET developers are using them on their sites. We know that both jQuery templates and partial views can achieve same result. There are even many blog posts that cover the details of jQuery templates, so I am not going to explain them here. Instead, I am going to show you when it is convenient to use jQuery templates and/ or partial views.
Client-side templates vs. partial views
As you might know, jQuery templates can be thought as client-side view engine. Sometimes jQuery templates can complicate your code and may not bring you any benefit at all. They can be handy though if you know when to use them. Here are some guidelines that will help you decide:
- Use jQuery templates if you are going to modify or refine the information returned from server before rendering to HTML. For example, if you have a list of items (eg books), you might need to modify their order or adjust time to browser’s local time before showing them, you will need to parse them on the client using some tool like jQuey templates.
- Use jQuery templates if you need to show same information in more than one part of the DOM even if you are not planning to modify this information. For example, To render a list of books as table rows (
<tr>) and as list items (
<li>) at the same time, you will normally return a JSON containing an array of the books, and then parse it using two different views and show the lists in their corresponding parts in the DOM. However, partial views cannot do the same thing at the same time, it would require another round trip to the server which is not efficient.
- Use jQuery templates when you want to pull data from 3rd party servers like twitter. For example, you can load tweets on the client using JSON format and then parse them using jQuery templates. You are unlikely to send this information (tweets) back to your server for the sake of rendering to HTML. It would be superfluous. However, if your server is acting as a proxy, a one that fetches tweets directly from twitter, it makes sense to use partial views.
Recall that jQuery templates are much more flexible than partial views, but also more tedious. Sometimes they are not necessary and sometimes they are really handy. It is a trade-off between flexibility and complexibility. But you can also mingle between partial views and jQuery templates in your website.