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 ...
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.