Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Building HTML with templates versus building it in javascript?

I recently started making web apps, and while I make some stuff that works, I'm not sure of the best practices.

Up to now, I've mostly used the templating systems of Django, web.py and PHP. But now that I'm using jQuery and nice ajaxy magic to get data from the server without refreshing the client, I'm seeing the advantages of building the HTML directly in javascript (so I can just send a small json object to the client and have him figure out what to change and how).

So now I have some bits that are rendered with templates, and some that are built in javascript, and even one horrid case where there's a mix of both, a web.py template that generates a javascript function that creates a HTML table - feels like C macros all over again! (I'll refactor that away eventually)

Is this a common problem in web development? Any recommended best practices, such as "use json for everything, render as much as possible in javascript", "use library foo", etc.? Any good heuristics for what to handle with templates, and what to handle with javascript?

Searching a bit here, I found someone asking about javascript templates, which does seem like a possible solution.

like image 205
Emile Avatar asked Nov 21 '10 20:11

Emile


People also ask

Should I use HTML template?

First of all, using a template tag makes it very clear that the HTML inside of it is used in JavaScript in order to render dynamic content. Secondly, the template tag has very handy methods for copying the content inside of it so it can be added to the DOM repeatedly.

What are HTML templates used for?

The <template> HTML element is a mechanism for holding HTML that is not to be rendered immediately when a page is loaded but may be instantiated subsequently during runtime using JavaScript. Think of a template as a content fragment that is being stored for subsequent use in the document.

What is template based in JavaScript?

JavaScript templating refers to the client side data binding method implemented with the JavaScript language. This approach became popular thanks to JavaScript's increased use, its increase in client processing capabilities, and the trend to outsource computations to the client's web browser.


1 Answers

Please, don't use Javascript to layout your pages. Only use it where it is needed.

Despite recent enhancements and standardizations, Javascript is still typically slow, difficult to be completely compatible (think old IE and others), and not so compatible with some screen readers and scrapers/search engines.

If you can do it by returning straight-up HTML, then that is typically the way you want to go.

like image 183
Brad Avatar answered Oct 14 '22 02:10

Brad