Template view pattern

From CSSEMediaWiki
Revision as of 10:11, 19 October 2010 by Martin Doms (Talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search
Template View - The template page typically references a helper object, which in turn references model objects. The helper delegates business logic back to the model.
In Template View, static HTML pages are defined and markers are used as placeholders within them for dynamic content on the page. When the page is requested, the markers are replaced with the dynamic content (ie, from a database or similar) by the underlying web server or framework. Common examples of this pattern are JSP, ASP and PHP pages.

Template View has already been implemented many times over in various languages and frameworks. As such, Fowler does not discuss how to implement this pattern, but gives guidelines on how to use it effectively. Some of these include:

  • If working with graphic designers who are more comfortable with XML-like markup and WYSIWYG tools capable of dealing with XML, try to use implementations with XML-like syntax, such as ASP.
  • Avoid embedding business or domain logic into the page in the form of scriptlets, which are capable of executing arbitrary code in the page. Instead, use helper objects on the backend to perform business logic. This prevents you from mixing business and UI code.
  • Avoid conditional logic in the template view. This is for the same reason as above - conditional logic is dangerously close to being business logic, and should be handled by helper objects. This is not always avoidable, but is considered a code smell.
  • Favour markup in the helper object output to logic in the template view. Although both scenarios involve mixing of concerns among layers, the former is often less objectionable.
  • Beware of exceptions. Try to catch all exceptions in your helper object. Exceptions in embedded page logic can be very difficult to debug, so again, avoid embedded scriptlets.


Template view is often used as the view portion of web-based Model view controller implementations. Popular examples of this are Ruby on Rails' templates and the view engines in ASP.NET MVC. The main alternative to Template View in this scenario is Transform View.

Personal tools