Chapter 5. Views and Templating

Views are the interface to your application; they’re what the end user actually interacts with and sees. In our case, views are logicless HTML fragments managed by the application’s controllers, which deal with event handlers and interpolating data. This is where it can be quite tempting to break the MVC abstraction by including logic directly into your views. Don’t succumb to that temptation! You’ll end up with senseless spaghetti code.

One of the biggest architectural changes you’ll have to make when moving server-side applications to the client side is with views. Traditionally, you could just interpolate server-side data with HTML fragments, creating new pages. However, views in JavaScript applications are somewhat different.

First, you have to transfer any data needed for the view to the client because you don’t have access to server-side variables. This is generally done with an Ajax call, returning a JSON object, which is then loaded by your application’s models. You shouldn’t be prerendering any HTML on the server side, but rather delegating all of that to the client. This will ensure that your client-side application isn’t reliant on the server for rendering views, keeping its interface snappy.

You then load that data into your views, either by creating the DOM elements dynamically with JavaScript or by using templates. I’ll elaborate on those two options below.

Dynamically Rendering Views

One way to create views is pragmatically via JavaScript. ...

Get JavaScript Web Applications now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.