Skip to main content

View

24th September 2013 by Luke Morton

Some thoughts on the view triad. That is templates, models and template engines.

Let's talk about templates first. Templates are the structure for your data. In a web application your templates will mainly be HTML or JSON focused. You might use mustache templates or maybe some old erb. For JSON you might use rabl. Here is a mustache example of a template for this blog. It's the post.mustache template used on this page in fact.

Pretty simple. The {{placeholder}} tags are there to be replaced by actual content. Content produced by a view model. A triple mustache tag is also used, {{{content}}}. This is a tag that does not escape it's HTML output into HTML entities. Mustache is safe by default you see. Anyways...

Where does the data used to replace these placeholders come from? Well this leads us onto a PHP class, the PostViewModel. View models model data for the view funnily enough.

As a quick aside, I mainly blog in ruby. But I made this website with PHP. For this article I'm using real code. I chose PHP – let's see what you think.

So this view model transforms markdown blog post content into HTML and formats the created timestamp into a sring. It then returns these as well as other data in the form of a hash.

This data produced by #as_array then needs to be consumed by a template engine and mixed with the post.mustache template.

So here we have the merging of template and view model by a template engine. In this case it is Phly's implementation of mustache in PHP. We also inject in Michelf\MarkdownExtra to render the post content.

Brief roundup

What do you think? Fairly simple I think. Three things:

  • template to structure your output
  • view model to adapt data for your template
  • template engine to mix the template and view model

This simple separation of concerns within the view logic of your code will lead to neater applications.

Templates structure your data. They know very little about your view logic. Keeping them this way you'll be able to reuse them more often and not have to worry when changes happen behind the scenes.

View models handle the data behind the scenes and provide a simple interface for template engines to consume the data they have rendered.

Template engines know one thing only. How to mix templates and view models. They are obviously coupled to the type of templates you use. You can't exactly parse mustache with a markdown template engine.

Are you building the views to your applications like me? Let me know if you are or if not what you are doing instead @LukeMorton.

Final note

I've been calling this the view triad. I also abbreviate to:

V = T + M + TE

Not so abbreviated huh? There are a couple more equations in my head that I'll write about soon. Ciao ciao.


Sign up for new content weekly

I'll only use this to send you guide updates