bldzrr
bldzrr

Reputation: 25

Why do web applications often use a separate template language to generate web pages?

Why do web applications use a separate template language to generate web pages (such as Jade) rather than using the language of the application (e.g., Java, Python, JavaScript)? I would just like to know if there is an actual reason or if it's just to have the logic (javascript) separated from the display code (jade/html)?

Upvotes: 2

Views: 163

Answers (1)

Brad
Brad

Reputation: 163262

Different tools for different jobs.

Your application languages are not all that suited to templating. It's easier to use something else, particularly if you use the style of language where you insert variable data into HTML, like Swig:

<h1>{{ headingText }}</h1>

To do this in JavaScript, you'd first have to create the node, then set its value. Do that for the whole document and it gets tedious.

var headingEl = document.createElement('h1');
headingEl.textContent = 'woot';
document.body.appendChild(heading);

Another reason is the folks making the templates are often different from those building the applications. Using a templating language that embeds variables into HTML is quite easy for a non-developer to pick up if they already know HTML. It's possible to let a web designer or technician level person go and make the templates, sticking in the variable data as-needed. Whether or not this matters to you depends on your needs.

There are those template languages, such as Jade, which require a very structured DOM build-up. While this guarantees a parsable document at the end, it can be a bit foreign to folks coming from building static pages. If you are using something as Jade, building the DOM in this way is still more convenient than creating nodes.

You could argue that it is easy to programmatically generate a page from data... say from JSON. You would be quite right, and in fact there is code that does just that. There is certainly nothing wrong with using it.

On a side note, Rasmus Lerdorf has famously argued that no templating engine is needed for PHP, because PHP is effectively a templating engine. Now, that's a bit out of context since PHP is a lot more mature than it used to be, and Rasmus was arguing against the template engine folks that were basically building a web framework into the templating. But, the idea of just using your application language directly is out there.

Upvotes: 1

Related Questions