Web Views as Data

HTML provides a semantic structure around data presented on the web. We can build on this to create a simpler presentation layer that avoids the need for complex view logic. Consider this bit of HTML:

The semantics of this simple fragment provide us with a basic understanding of the data that will be presented. We can think of the ‘article’ as representing a unit of content, each unit containing a heading and a body.

If we think of the ‘article’ as representing a data object, we can let the data itself drive the rendering process. Doing this requires a bit more knowledge though, since we need to know what part of the data each node represents. We can do this with HTML data attributes:

Now we can parse the view template into a structure; something like this:

Rendering is now a matter of transforming the view structure to match the data that we want to present. Once the view and data match, final presentation happens by mapping each value into its respective node:

When we treat the view as data, rendering is replaced with a transformation of one data structure into another. Given a view template and some data, complex rendering can be expressed as simple presentation:

We only have to say what should be presented and the data drives the rest of the presentation process. Interested in seeing this in practice? Take a look at Pakyow, a web framework built around this approach.

[originally published at notmagic.org]