Suppose I got a div that uses AJAX to retrieve prices and information about products, and appends the new products to current results.
<div id="product">
<div class="label">Price: <div class="price">$10.90</div></div>
<div class="label">Sales Price: <div class="price">$9.90</div></div>
</div>
I can do: 1) Get the price and data only. Then iterate through these results and have the Javascript create the div dynamically for each product.
Problem with this: If HTML structure for the div changes (say the class for price changes), I potentially need to change it in 2 places. In the static HTML, as well as in the Javascript.
2) Or is it better practice to have the server return the actual HTML to append to the page? But wouldn't this be messy because the design isn't separate from business logic, and the actual HTML structure might change?
Or is there a 3rd alternative I'm missing?
You can use java-script side templating - there are lots of libraries. I will recommend looking at John Resig's approach. I believe there is also work going on jquery based template engine.
You may also read Rick Strahl's experience here and also the comparison of various template libraries.
Although java-script based templating is elegant solution to your problem, if you have to support java-script disabled scenario then your option #2 is good bet. Generally, you use server side templating to generate the html for first request as well as ajax request (so html structure is maintained only at one place i.e. server side template). Of course, in js-disabled scenarios, your ajax calls will become regular POST requests.
You may want to consider JavaScript templates. Check out http://code.google.com/p/trimpath/wiki/JavaScriptTemplates
You can just have JSON passed back from the AJAX call, and let the template do the hard work. That way you only have one place to change classes in the HTML.
Happy coding!
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