<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>getiblog &#187; templating</title>
	<atom:link href="http://blog.getify.com/tag/templating/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.getify.com</link>
	<description>open-source, performance, javascript &#38; ui musings</description>
	<lastBuildDate>Mon, 23 Aug 2010 20:50:24 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Grab UI by the Handlebar</title>
		<link>http://blog.getify.com/2010/02/grab-ui-by-the-handlebar/</link>
		<comments>http://blog.getify.com/2010/02/grab-ui-by-the-handlebar/#comments</comments>
		<pubDate>Sun, 21 Feb 2010 21:53:03 +0000</pubDate>
		<dc:creator>getify</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[UI Architecture]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[templating]]></category>
		<category><![CDATA[ui architecture]]></category>

		<guid isPermaLink="false">http://blog.getify.com/?p=234</guid>
		<description><![CDATA[A couple weeks back, I talked about HAML and why I&#8217;m not a fan of its approach. I promised in that article that I would be following up with some discussion of how I think UI templating should work. I intended to post earlier than this, but then I dove into a fun new coding [...]]]></description>
			<content:encoded><![CDATA[<p>A couple weeks back, I talked about <a href="http://blog.getify.com/2010/02/why-i-dont-like-haml/">HAML and why I&#8217;m not a fan</a> of its approach. I promised in that article that I would be following up with some discussion of how I think UI templating <em>should</em> work. I intended to post earlier than this, but then I dove into a fun new coding project (which I will write about here soon), and I&#8217;m just now resurfacing for air.</p>
<p><strong>Disclaimer</strong>: The criticisms I have of various web application frameworks and platforms are not <em>entirely</em> universal. There <strong>are</strong> some solutions out there which have vastly improved their approaches. For instance, I&#8217;ve borrowed some good parts from Django, <a href="http://github.com/janl/mustache.js">Mustache.JS</a>, even (whisper) .NET MVC. The problem is, the bad stuff is so overwhelmingly prevalent in the development community, it chokes out the life of those who really are trying to make it better. Add my voice to <em>that</em> list, and a +1 for all the others who are on that same page.</p>
<p>This will not be a simple quick post. There&#8217;s so much I need to write, and it just can&#8217;t all fit into a few paragraphs. Please bear with me as I expound on this topic.</p>
<h2>Handlebar?</h2>
<p>Before I go into further explanation, go check out <a href="http://github.com/getify/HandlebarJS">HandlebarJS Template Engine</a>, my entry into the arena of how to construct web UI. It&#8217;s important to note, this is <strong>not</strong> some &#8220;Yet-Another-&#8221;  all-in-one framework that has sexy themeable widgets, a CMS, or auto-generated admin interfaces. All you will find there is a basic, simple Templating Engine, that takes JSON data as input, processes and compiles text-based templates (that you create and control 100%) into &#8220;executables&#8221;, and pumps the JSON data into the compiled templates to return a &#8220;View&#8221;.</p>
<p>There&#8217;s much more planned for HandlebarJS, including tools for build-processes, filters, compression, UI optimization, etc. They will come in the form of loosely coupled &#8220;plugins&#8221; that are compatible with HandlebarJS&#8217; &#8220;view&#8221; of the world.</p>
<p>HandlebarJS is really quite the opposite of most UI frameworks: it&#8217;s a stripped down, deconstructed, anti-framework tool for what is now being called the &#8220;middle end&#8221; &#8212; the stuff that sits between the front-end and the back-end, and negotiates communication, View construction (templating), URL routing, data validation, and other fun things. </p>
<p>What HandlebarJS is <strong>not</strong> is <em>any</em> kind of RIA framework that attempts to handle the behavioral side (JavaScript) of rich UI. HandlebarJS is only concerned with as quickly and efficiently as possible generating the markup for the UI.</p>
<p>HandlebarJS is intended to be one of several independent components for re-thinking the middle-end UI architecture of web applications. Those other components deserve their own full projects and explanations/write-ups, so you&#8217;ll just have to keep an eye out here over the coming weeks for those.</p>
<h2>Why should I care?</h2>
<p>You may ask yourself at this point: &#8220;I have XYZ framework or platform (.NET, Java/Swing, RoR, Django, etc) already, and it does all that stuff for me. Why do I need something else?&#8221; Well, that&#8217;s a great and valid question, one that deserves a lot more discussion than can ever fit into one blog post. I do have a very specific set of answers to that question, and I will be unveiling it little by little through blog posts (including this one), separate dedicated websites, and even an upcoming planned book.</p>
<p>For now, I&#8217;m going to ask you the reader to take my word just a little bit &#8212; that&#8217;s there strong reasoning behind what I&#8217;m trying to do &#8212; and let me develop and explain it bit by bit. This post will present some of the high level motivations and discuss specifically HandlebarJS for templating &#8212;  my goal for now is that you&#8217;ll come away more knowledgeable about <em>just <strong>an</strong> alternative</em> to how your web application currently approaches its Views. I&#8217;m not <em>yet</em> trying to convince you that you need an entirely different application architecture &#8212; we&#8217;ll get there slowly, and it won&#8217;t be as scary as it may seem.</p>
<h2>What am I trying to solve?</h2>
<p>I don&#8217;t want to re-write here the entire article and underlying arguments I had against the HAML approach. But, I do encourage you <a href="http://blog.getify.com/2010/02/why-i-dont-like-haml/">to read it</a> to understand better where I&#8217;m coming from.</p>
<p>However, here are the primary thoughts that were motivating factors for creating HandlebarJS:</p>
<ol>
<li><strong>DRY and Portability</strong>: For decades, the development community has operated (to varying degrees of authenticity and success) under the principle of not repeating yourself, meaning as much as possible, don&#8217;t have two different sets of code that do the same thing. The advent of functions/sub-routines laid the ground work years ago, upon which Object-Oriented programming expounded to give us even better patterns for write once, use many.
<p>The problem is, the explosion of the web application paradigm has thrown several wrenches into the mix. What fundamentally used to be a single monolithic application, or even a straightforward server-client application, is now a highly complex, distributed, cloud-integrated, web connected, desktop and mobile consumed, rich, thin-and-thick application conglomeration that challenges with orders of magnitude more complexity than our older patterns are capable of handling. It&#8217;s almost like we went from n-tier to n^2-tier architecture in a relatively short period of time.</p>
<p>Moreover, the paradigm of the presentation layer residing in a browser has both extended <em>and</em> limited the evolution of such applications. For several years, even after the invention of Ajax (which revolutionized the page-refresh), web developers have struggled with wanting to do more with Rich Interfaces than the browser (or even internet connection or host computer) was capable of handling. The latest generation of browsers, web technology standards, and computing equipment has finally broken down many of those barriers.</p>
<p>But just as we finally got to the point where the desktop web browser could be an effective tier in the overall application (not just a thinly veiled client), now we have an intense push to extend all our web application presences into a new frontier of &#8220;connected&#8221; devices (mobile, smart phone, netbooks, etc), many of which are (in some ways) throw backs to the performance (CPU, connection speed, etc) we could rely on with desktop browsers 5 and 8 years ago. </p>
<p>Even as mobile Safari pushes to implement the latest and greatest HTML5/CSS3 standards, the reality is that mobile web apps are still handcuffed by limited processor capacity, severely limited browser caches, and unreliable (at best) connectivity.</p>
<h3>So what does all this have to do with DRY and portability?</h3>
<p>I believe we are at an inflection point in the web UI evolution where we must start to think about things differently if we have any hope of keeping up with the exponentially complicating trends of consumer technology. We&#8217;re starting to see the fundamental inadequacies (and the pain it brings) of established solutions, in their inability to efficiently handle the rapidly expanding array of consumers of UI presentation.</p>
<p>These all-in-one frameworks are so attractive to development teams because they fully abstract away all of the messy details of how markup and data are combined to be the delivered UI product. But with that ease-of-use comes a price &#8212; lack of flexibility to control and optimize such UI delivery on the fly depending on who is consuming it. A fancy .NET list widget may rock for UI delivered in IE8 on a desktop, but is it up to the task of usable and functional behavior/display in a mobile Opera browser on a screen 1/16 the size of a laptop screen and with 1/10 the memory and CPU? The sad answer is often: absolutely not.</p>
<p>And no, it&#8217;s not enough to just have a different stylesheet for mobile browsers and expect that CSS will save the usability of your app. Mobile (narrow-screen) is an entirely different paradigm in almost all respects to desktop computing. To effectively leverage both platforms simultaneously, <strong>AND</strong> with the same (unrepeated) code bases, we&#8217;re gonna have to get a lot more creative.</p>
<h3>&#8220;And now, for something completely different&#8221;</h3>
<p>We need an approach to UI that is powerful yet compact, that is portable (meaning it can run in both a server environment and in a variety of browser host environments), and that is flexible enough to be extended/composed/dissected/etc as necessary for the different devices consuming the UI. This isn&#8217;t just an incremental improvement on existing systems, it&#8217;s an entirely new new kind of approach.</p>
<p>Of course, if you <em>prefer</em> to write code over and over again, and maintain different application branches for different presentation consumers, then you&#8217;ll probably totally disagree with me here &#8212; you&#8217;d probably rather just stay the course. But I think the future is more re-use and convergence, not less. And I make no apologies for the fact that this is my <strong>fundamental bias</strong> for everything I&#8217;m trying to do here. I <em>do not</em> like at all to <em>Repeat Myself</em>, and I&#8217;m going to do everything I can to keep that out of my development practices.</p>
<p>And I&#8217;m just crazy enough to believe in the idealism that it IS possible to achieve this utopia. We&#8217;re just gonna have to be brave enough to question everything we&#8217;re currently doing. No big deal, right?
</li>
<li><strong>Do front-end type work in&#8230;&lt;gasp>&#8230;ONLY front-end technologies</strong>: I feel like I&#8217;m probably admitting frequently on this blog to not only being strongly opinionated but also a little bit crazy. But that&#8217;s ok with me. I can tell you we are not gonna ever solve any real problems by thinking the same way we always do. And I like that I&#8217;m a fundamentalist &#8212; that I believe less is more.
<p>I think we could use a lot more of that mindset in the development community. You wouldn&#8217;t get in a jet-liner to travel up to the corner store &#8212; so why do we feel that these immensely complex frameworks and platforms are the right approach to web applications?</p>
<blockquote><p>
Perfection is achieved, not when there is nothing more to add, but when there is nothing left to take away.  &#8212; Antoine de Saint-Exupery
</p></blockquote>
<p>Let&#8217;s face it: we all (at one time or another) entertain dreams that <em>our</em> web application is going to need to scale to hundreds of millions of concurrent requests, and our development team is going to balloon to hundreds of distributed development groups, and we must <em>plan</em> for that now by using an enterprise-ready <em>Solution</em>.</p>
<p>Yet, when you look at the world&#8217;s biggest web applications &#8212; the Googles, the Yahoos, the Facebooks, and the Twitters of the world &#8212; you actually don&#8217;t see them using such non-sense to drive their applications. In fact, you often see fundamentalism blatantly plastered across their approach. Why? Because as things scale, what&#8217;s not needed is <strong>more</strong> machinery to manage it, but <strong>less</strong> to abstract away and play middle-man in the transformation of a request into a response.</p>
<h3>This post is about UI, right?</h3>
<p>Nowhere is this more true than in the UI layer (the middle-end). It&#8217;s been recently suggested by <a href="http://stevesouders.com">Steve Souders</a> of Yahoo and Google fame that actually most of the performance bottle necks (of small and large applications alike) is the UI layer.</p>
<p>My thesis: the fewer layers of abstraction sit on top of the presentation layer, the more efficient the application will operate (in both low and heavy traffic situations). My corollary: This fundamentalist approach to UI will <em>also</em> lead to better separation of skillsets &#8212; a front-end engineer can completely control the UI of an application using <strong>only</strong> front-end technologies like HTML, JavaScript, and CSS, which they are likely best at. </p>
<p>This means that when they want to streamline the way their UI is constructed and delivered to address a page-load efficiency issue on their site (like JS/CSS concatenation for instance), they can get directly and immediately to the problem, <em>in the front/middle-end layer</em> (instead of wading through who knows how much back-end cruft that they may or may not be fully capable of navigating or changing). They can also use the technologies they are likely most familiar with (their core skillset) to solve the issues.</p>
<p>This may seem like a trivial distinction. But I believe it&#8217;s a critical and overlooked factor in developer efficiency: staying within one&#8217;s core skillset &#8212; the sweet spot &#8212; as much as possible. And this doesn&#8217;t just apply to developers but to technologies as well. I believe there&#8217;s a reason that Java largely didn&#8217;t survive as a pure front-end technology, and why there hasn&#8217;t been a pig push by the community to bring native Ruby processing to the browser. These technologies have their place, but the browser is not that place.</p>
<p>Whether you like JavaScript or not, it&#8217;s quite clear that it is uniquely and best positioned to service all the needs that the UI layer needs. And as you&#8217;ll see in a little bit, that means both in browser and on the server. You may not ever (want or need to) re-write your hundreds of thousands of lines of Java, but I hope maybe you&#8217;ll consider delegating your UI code to the technology that rules the UI. </p>
<h3>&#8220;Both-enders&#8221;</h3>
<p>I can just hear some of you right now: you&#8217;re the ones who wear both the hat of front-end developer and back-end developer (sometimes at the same time). For you, it&#8217;s no big deal at all to &#8220;context switch&#8221; mentally and use back-end technology (like a JSP taglib) to generate your front-end. In fact, if you&#8217;re not a <em>specialist</em> in UI technologies, that may be more comfortable and productive for you to do so.</p>
<p>I don&#8217;t claim that I can convince you otherwise. But let me just submit to you this suggestion: is it possible that you might be more efficient at your UI hat tasks if you didn&#8217;t have to concern yourself at all with back-end architecture issues? And vice versa, would your back-end work be more fun and efficient if you didn&#8217;t have to constantly worry about markup, box model quirks, or cross-browser JavaScript&#8217;ing? </p>
<p>I think it would. In fact, I&#8217;m almost certain of it (at least the UI hat side of things). I&#8217;ve worn both hats many times in many different jobs. And I can tell you that unequivocally, I was noticeably more efficient when I had the ability to only wear one hat any given time. What is good for the back-end is often times irrelevant (or bad) for the UI, and vice versa. They are two entirely different disciplines, and it&#8217;s time we admit that. Not that you can&#8217;t do both, and effectively, but just that you can&#8217;t do both <em>at the same time</em> effectively.
</li>
<li><strong>Stop meddling in <em>my</em> code</strong>: Probably my biggest issue with how most frameworks and platforms approach templating is that the templating engine is deeply embedded in, and hopelessly intertwined with, the back-end technology. This invariably leads to far too often bending/breaking the fundamental rule of the MVC pattern (keep the View, Controller <em>and</em> Model <strong>separate</strong>).
<p>For instance, consider PHP as a simple example. PHP <em>is</em> a templating engine (if you weren&#8217;t already aware). It allows you to take a predominantly HTML file and litter any manner of PHP code logic all throughout it. <strong>THIS IS NO BETTER THAN THE SPAGHETTI CODE OF QBASIC FROM 20 YEARS AGO.</strong> You actually have to fight hard against these urges (and pretty much every tutorial on the web), and go to great lengths to keep your templates free from such mess.</p>
<p>And why go to this trouble, you may wonder? Let me give this example:</p>
<pre style="background-color:#ddd;">
&lt;div id="#controls">
   &lt;?php if ($user->IsLoggedIn() &#038;&#038; $user->CanPublish()) { ?>
      &lt;a href="publish.html">Publish&lt;/a>
   &lt;?php } ?>
&lt;/div>
</pre>
<p>Seems harmless enough, right? <strong>WRONG.</strong> This is pure and undefiled evil. You think that just because you put the login session logic and access control logic into your Model (wait, shouldn&#8217;t that <em>actually</em> be in the Controller???), and you merely call and use those methods in your template, you&#8217;ve achieved separation? <strong>WRONG.</strong></p>
<p>Why do I feel so strongly? Because this pattern is blatantly opening up the doors to putting Controller (and Model) logic right inside the View. First of all, your front-end developer (if that&#8217;s not also you Mr. Back-end Engineer) has to know something about your back-end technology (PHP in this case) &#8212; and in some cases, they need to know <strong>a lot</strong> about the back-end to even accomplish a small UI task. This is <em>probably</em> not his or her core skillset (see #2 above), so it&#8217;s bound to slow down the efficiency of UI work. </p>
<p>Also, you have now tied business logic into your View, which is against proper patterns we all learned in Software 101. Consider this scenario (which is so common it&#8217;s almost self-obvious): The View developer writes code like the above. Then he leaves the company. </p>
<p>6 months later, a back-end developer goes through and refactors the Model. He decides for one reason or another that Access Control Permissions are now going to be exposed in the Model (ie, across all the back-end code) as a bitmask property upon which efficient bitwise operators (| &#038;) can be used to figure out permissions. Because they want to keep the back-end code pure and efficient, and don&#8217;t want unnecessary methods literring the Model, they <strong>remove</strong> the <span style="background-color:#ddd;">$user->CanPublish()</span> method. No problem, right? We just do a grep/code search and find all instances of CanPublish(), and we change that code to instead be <span style="background-color:#ddd;">($user->perms &#038; USER_CAN_PUBLISH)</span>.</p>
<p>Ugh. If this doesn&#8217;t scream out at you as bad, I don&#8217;t know what planet you develop on. It gets worse. 6 months later, the back-end developer quits, and shortly thereafter, the business folks decide that a user must have both USER_CAN_PUBLISH permission and <strong>not</strong> <span style="background-color:#ddd">($user->restrictions &#038; USER_IS_DISABLED)</span>. I bet at this point, the new back-end developer instead gives in and creates a method <span style="background-color:#ddd;">$user->CanPublishAndEnabled()</span>. Yet more Controller/Model logic hopelessly embedded in the View. And yet another round of View refactorings. I bet your front-end developers (who don&#8217;t know much PHP) are getting annoyed by now. Are you seeing the pattern?</p>
<p>What if instead, there was a pre-agreed-upon <em>Boolean</em> property in the View data (ahem, not Model), called &#8220;allow_publish&#8221;. The Controller takes care of setting that property (with whatever logic is appropriate at that moment in time) before it invokes the View, and it just passes along that Boolean flag to the View. Then, no matter what kind of back-end refactorings or logic changes occur, the View always look like this:</p>
<pre style="background-color:#ddd;">
&lt;div id="#controls">
   &lt;?php if ($data["allow_publish"]) { ?>
      &lt;a href="publish.html">Publish&lt;/a>
   &lt;?php } ?>
&lt;/div>
</pre>
<p>The difference may seem subtle, but it&#8217;s actually enormously important. While I&#8217;d definitely call this an improvement, there&#8217;s definitely more we can (and should) try to achieve.</p>
<h3>But, my MVC can do that</h3>
<p>The point is not <em>really</em> whether your current environment <em>can</em> do what I&#8217;m suggesting. The point is that it probably <em>isn&#8217;t</em>, and moreover, it probably feels easier to all involved if it doesn&#8217;t. Otherwise, you probably wouldn&#8217;t still be reading this article, because you&#8217;d be so furiously effciently coding away in your utopian development environment and would have no desire to read my crazy ramblings on the topic!</p>
<p>I believe we need to encourage Templating Engine solutions to be absolutely minimalist on the amount of &#8220;programming&#8221; they allow in the Views. The bias should be: allow only the bare minimum of logic as is necessary to select templates and fill them with data. If it&#8217;s any harder than that, then it&#8217;s logic that belongs back in the Controller (or deeper). Sure, you need basic things like boolean logic for selecting sub-templates, simple looping constructs, and such. But you don&#8217;t need the ability to call functions, invoke complicated, deep instantiation heirarchies of mixed Models, run math computations, or any of that non-sense. <strong>Remember</strong>: Jet-liner to the corner store.
</li>
</ol>
<h2>Nodding off</h2>
<p>OK, so at this point, you must be exhausted reading this post. I&#8217;m exhausted writing it. I promise I&#8217;m gonna wrap up quickly. I know it&#8217;s a lot of information to take in, but I&#8217;m intensely passionate that it needs to be said, and these questions and issues <em>need</em> to be addressed.</p>
<p>This article has thus far been almost entirely me laying out the reasons why I didn&#8217;t like <em>most</em> of the templating solutions that are common across the vast majority of web application frameworks and platforms. This is by far not an exhaustive list of the problems, but those 3 points above are a pretty good summary of the <em>types</em> of problems motivating me to find and present another way.</p>
<p>So, if you&#8217;re still with me after all that, let me try to briefly explain how I believe HandlebarJS addresses these concerns (and others).</p>
<h2>Finally, some Handlebars</h2>
<p>HandlebarJS gets its name as the upside down mustache (from <a href="http://github.com/janl/mustache.js">MustacheJS</a> templating). The { and } are the things of which we speak.</p>
<p>Here&#8217;s what you should know about HandlebarJS:</p>
<ol>
<li>HandlebarJS is <em>entirely</em> written in JavaScript. In fact, it&#8217;s entirely written in a manner that allows it to run in either a synchronous or asynchronous environment, either in the browser or on the server (using any of several available server-side JavaScript environments). This allows the exact same code base to run either in browser or on server. Period. Doesn&#8217;t get any more DRY than that. You can do templating in either place, or both, as your application requires.
<p>It&#8217;s small and portable and so should be suitable for your templating tasks in a wide variety of JavaScript friendly environments, including even (and especially) mobile.
</li>
<li>It follows naturally that since the HandlebarJS code is portable and identical both in browser and on server, the templates themselves are also identical. Absolutely. The templating &#8220;language&#8221; is simple but expressive and capable of any tasks you should rightly tackle with templating. And so you can write your templates once, and run/interpret them in any HandlebarJS capable environment. Again, this is <em>really</em> DRY.
</li>
<li>HandlebarJS accepts JSON data, and only JSON data, as its input. This means that any platform/environment which can serialize its Model/data down to JSON can send that data to a HandlebarJS instance and get back a processed template View output. Pretty much every language on the planet has JSON serialization/de-serialization support built-in (or at least available easily). JSON data is also the <em>only</em> format of data that is fully and natively portable from server to browser.
<p>That&#8217;s right, some browsers (and clients) don&#8217;t natively understand XML even, but they <em>all</em> understand JavaScript, and thus all understand JSON data. Why go to the inefficient trouble of wrapping your data up in some other non-natively-parseable data abstraction? Just use JSON. Trust me, there is no other format better for the task.
</li>
<li>HandlebarJS is built with simplicity and efficiency in mind. The templating language is as simple as possible to get the job done. It doesn&#8217;t give you too much rope to hang yourself. You really can&#8217;t embed Controller or Model logic in these Views.
<p>Also, HandlebarJS compiles templates from their text files into executable JavaScript snippets. This &#8220;compilation&#8221; can be done on the fly (in either browser or server) if necessary, or it can be done as part of a build-process to increase efficency. HandlebarJS will operate the same functionally regardless of whether it&#8217;s dealing with pre-compiled templates or needing to compile them on-demand.
</li>
<h2>Fin</h2>
<p>OK, that&#8217;s it, I&#8217;m done, I promise. I hope by this point you&#8217;re at least convinced it might be a good idea to take a look at HandlebarJS. Even if you are still certain that your existing application architecture is sufficient and won&#8217;t need to change, perhaps you might consider exploring if just the View portion can, in whole or in part, be separated off and delegated to a HandlebarJS instance. </p>
<p>If you only want to use HandlebarJS in the browser, you can do so without any architectural/server changes at all. Just drop it into an existing page and start converting your existing templates one-at-a-time. See how easy it is!</p>
<p>And absolutely the only required dependency for HandlebarJS (on the server) is a simple server-side JavaScript environment (many options are available). In fact, keep an eye for the next blog post here, as I will be discussing my brand new released <a href="http://github.com/getify/BikechainJS">BikechainJS</a>, which is a SSJS wrapper around the V8 JavaScript engine, allowing drop-dead simple JavaScript execution on the server. HandlebarJS and BikechainJS are specifically built to be simple and compatible.</p>
<p>Seriously, stop reading this blog post <strong>now</strong> and go <a href="http://github.com/getify/HandlebarJS">check out HandlebarJS</a> &#8212; isn&#8217;t it about time for you to grab your UI by the &#8220;Handlebar&#8221; and make it do what you want?</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.getify.com/2010/02/grab-ui-by-the-handlebar/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Why I don&#8217;t like HAML</title>
		<link>http://blog.getify.com/2010/02/why-i-dont-like-haml/</link>
		<comments>http://blog.getify.com/2010/02/why-i-dont-like-haml/#comments</comments>
		<pubDate>Thu, 04 Feb 2010 19:38:52 +0000</pubDate>
		<dc:creator>getify</dc:creator>
				<category><![CDATA[Misc]]></category>
		<category><![CDATA[UI Architecture]]></category>
		<category><![CDATA[architecture]]></category>
		<category><![CDATA[html]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[template]]></category>
		<category><![CDATA[templating]]></category>
		<category><![CDATA[ui]]></category>

		<guid isPermaLink="false">http://blog.getify.com/?p=168</guid>
		<description><![CDATA[Disclaimer
Before I begin, let me share my personal mantra: &#8220;everyone is entitled to their own (wrong) opinions.&#8221; This includes me. This post is purely opinion. It&#8217;s an editorial. It means nothing unless you care what my opinion is. If you&#8217;re easily offended, or if you just love HAML, or if you&#8217;re a closed minded bigot, [...]]]></description>
			<content:encoded><![CDATA[<h2>Disclaimer</h2>
<p>Before I begin, let me share my personal mantra: &#8220;everyone is entitled to their own (wrong) opinions.&#8221; This includes me. This post is purely opinion. It&#8217;s an editorial. It means nothing unless you care what my opinion is. If you&#8217;re easily offended, or if you just love HAML, or if you&#8217;re a closed minded bigot, or whatever, just move on. Really. </p>
<p>I really don&#8217;t care what your opinion is on this topic, I just want to express mine, for the record, for posterity sake. And I&#8217;m not trying to convince anyone to use or <strong>not use</strong> HAML. I simply want to state the things I dislike about it. </p>
<p>I&#8217;m a fundamentalist, and I prefer simplicity in almost all cases. My bias toward performance, customization, control, optimization, and other such ethics should be evident from this blog already. This automatically makes me suspicious of &#8220;all-in-one&#8221; anythings. I&#8217;m the anti-framework guy. I&#8217;m the anti-platform guy. I&#8217;m the guy who wants the bare minimum in place to get my task done effectively. And I believe that in doing so, with as few layers of abstraction (and processing) as feasible and possible, you will end up with more performant code. </p>
<p>But this doesn&#8217;t <em>have</em> to come at the price of less maintainable code. It&#8217;s just that for years, the development community has strived for more maintainable code, and the only answer we&#8217;ve ever figured out collectively is to put higher and higher levels of abstractions on things. </p>
<p>Some abstraction is good and smart (<a href="http://twitter.com/brandonaaron/status/8596115868">we don&#8217;t write 0&#8217;s and 1&#8217;s</a>, thanks @<a href="http://twitter.com/brandonaaron">brandonaaron</a>!!), but to the level that a lot of people take it, I liken it to using a pictures-only menu at a fast food restaurant. No offense to the foreign or illiterate, who I&#8217;m sure that is helpful to, but if you <em>can</em> read, you <em>should</em>. Pointing to the picture of a hamburger, then the picture of a ketchup bottle, then&#8230; this is inferior to just saying &#8220;Hamburger with ketchup&#8221;, if you <em>can</em> say that. Just my opinion.</p>
<p>Anyway, my goal with this post is to identify the fundamental approaches (not just nit-picking) of HAML that I dislike. Actually, to be fair, HAML is not the problem itself, HAML is just a symptom of the larger problem, convenient to help me illustrate some thoughts on templating as a discipline.</p>
<p>I&#8217;ll continue the discourse in subsequent post(s) with other opinions, and even some suggestions I have for solutions. Hopefully you&#8217;ll stick around and get something out of it. If not, that&#8217;s fine, too.</p>
<h2>Brief overview of HAML</h2>
<p>For those who aren&#8217;t aware, <a href="http://haml-lang.com/">HAML</a> is a templating language, apparently most closely associated with Ruby, that uses some &#8220;shorthand&#8221; to express HTML structures. It&#8217;s important to note that it&#8217;s more involved than a simple shorthand such as Wiki/<a href="http://en.wikipedia.org/wiki/Markdown">markdown</a>, as it appears aimed to be a full-fledged templating engine.</p>
<p>As it includes a templating &#8220;language&#8221; (a <a href="http://en.wikipedia.org/wiki/Domain-specific_language">DSL</a>, technically), it has the usual suspects, including variable replacement, logical selection operators, &#8220;sub-template&#8221; includes, comments, etc. It also allows/includes Ruby (or Ruby-like, not quite sure) syntax for more complicated logic, such as function definitions, looping, math operations, etc.</p>
<p>Let&#8217;s identify first the most important characteristics of HAML (at least, those relevant to my points):</p>
<ul>
<li>HAML uses CSS-like shorthand to reverse-declare HTML tags. (HAML assumes a &#8220;&lt;div>&#8221; tag type unless otherwise specified).
<p>Example:</p>
<pre style="background-color:#ddd;">
#mydiv
    %span.message
        Hello World
</pre>
<p>Would result in:</p>
<pre style="background-color:#ddd;">
&lt;div id="mydiv">
    &lt;span class="message">Hello World&lt;/span>
&lt;/div>
</pre>
<p>It&#8217;s easy to see how in this respect, the &#8220;shorthand&#8221; for the resultant HTML seems easier to write/maintain.
</li>
<li>HAML uses whitespace indentation nesting to signal scope of tag blocks. This is <strong>critical</strong> for HAML being able to know where a block ends without needing closing tags, a big part of the &#8220;shorthand&#8221; being achieved.
<pre style="background-color:#ddd;">
#mydiv
    %ol#mylist
        %li.myitem
            Hello
        %li.myitem
            World
</pre>
<p>Results in:</p>
<pre style="background-color:#ddd;">
&lt;div id="mydiv">
    &lt;ol id="mylist">
        &lt;li class="myitem">Hello&lt;/li>
        &lt;li class="myitem">World&lt;/li>
    &lt;/ol>
&lt;/div>
</pre>
<p>Again, clearly the &#8220;shorthand&#8221; syntax has some appealing aspects, so far. If you like/don&#8217;t mind &#8220;whitespace sensitive languages&#8221; like Python and VB, you&#8217;ll be ok with using indentation in place of closing tags.
</li>
<li>
For more complex tasks, like math operations, dropping in variable replacements, calling functions, executing logic, etc, HAML allows you to use an = sign to signal a line of Ruby code to be executed in the context of the template parsing, with the output being added to the template at that point. (You use a &#8211; to indicate Ruby that should execute but which returns no desired output to include in the template).</p>
<p>Example:</p>
<pre style="background-color:#ddd;">
- (42...45).each do |i|
    %p= i
</pre>
<p>Results in:</p>
<pre style="background-color:#ddd;">
&lt;p>42&lt;/p>
&lt;p>43&lt;/p>
&lt;p>44&lt;/p>
&lt;p>45&lt;/p>
</pre>
<p>There are other variations of how to include/execute Ruby code as well. The point is, HAML tries to make it pretty easy for you to execute logic in your template, as long as that logic is Ruby. Also, they make one little buried warning in the documentation about encouraging you not to run Ruby logic which <em>should be</em> in the Controller. It&#8217;s not enforced in anyway, but I guess if you read <strong>and</strong> obey, that&#8217;s helpful.
</li>
</ul>
<p>There&#8217;s certainly more (<a href="http://haml-lang.com/docs/yardoc/file.HAML_REFERENCE.html">a lot more</a>, in fact) to HAML than this short list. I&#8217;m not writing a book on HAML (or anti-HAML) here, so I&#8217;m just trying to keep it to a minimum. But let&#8217;s just suffice it to say, there&#8217;s a few dozen different syntax rules, tag types, practices, etc that are required to use a HAML template for a non-trivial task like building a full dynamic web app page. Also, you&#8217;re going to have to know Ruby to get much more than simple &#8220;shorthand&#8221; HTML out of the deal.</p>
<h2>My opinions</h2>
<p>I&#8217;m going to assume if you&#8217;re still reading this blog post at this point, you&#8217;re here because you a) care about my opinions, or b) care enough to want to discredit my opinions. If you&#8217;re in group (a), read on. If you&#8217;re in group (b)&#8230; well&#8230; refer back to the first sentence of the post about my personal mantra.</p>
<h4>Whitspace/indentation scoping</h4>
<p>So, first off, I hate, absolutely detest, cannot stand, whitespace-sensitive languages. I cannot think of hardly anything in programming paradigms that irks me more than having to try and determine a set of logic context and having to count the number of indented columns (if they are spaces and not tabs, for instance) to figure out which blocks go together. This is doubly true if you choose to use like 1 or 2 space indentation, which I&#8217;ve seen at a couple of my previous jobs. </p>
<p>I suppose if you used 10 spaces for each indentation mark, it might make things obvious enough, but then you&#8217;re defeating the purpose of trying to use shorthand if you have to add and manage a bunch of extra characters to help make scope identifiable.</p>
<p>This brings up my counter opinion: languages like C and JavaScript use just 2 characters to identify blocks; the &#8220;{&#8221; and the &#8220;}&#8221;. This also makes it easier for code editors to give you helpful hints like highlighting closing and opening &#8220;tags&#8221;, and helping you know if you have unbalanced/unclosed elements, etc. I like this in JavaScript and C styled languages, so it natually should extend that I like this in HTML.</p>
<h4>I don&#8217;t like complications</h4>
<p>The above examples look really nice, and are probably the sweet spot for how HAML shines. But if you read <a href="http://haml-lang.com/docs/yardoc/file.HAML_REFERENCE.html">the long form documentation</a>, you&#8217;ll quickly see that there are lots of other complicating scenarios which you must learn to deal with. Indeed, HAML is not just shorthand convenient HTML, it&#8217;s a DSL with sytnax and rules and exceptions and gotchas all its own.</p>
<p>For instance, consider the case of wanting to add some attributes to a tag. Here&#8217;s an example from the documentation of the proper way to do it with HAML.</p>
<p>Say you want this HTML:</p>
<pre style="background-color:#ddd;">
&lt;sandwich bread='whole wheat' delicious='true' filling='peanut butter and jelly' />
</pre>
<p>Just use this &#8220;little&#8221; snippet of goodness (makes me hungry just reading it):</p>
<pre style="background-color:#ddd;">
def hash1
    {:bread => 'white', :filling => 'peanut butter and jelly'}
end
def hash2
    {:bread => 'whole wheat'}
end
%sandwich{hash1, hash2, :delicious => true}/
</pre>
<p>Uhhh, wait a second. I thought HAML was supposed to be shorter and simpler. I dunno about you, but this does not appear shorter <strong>or</strong> simpler to me. Maybe that&#8217;s just because I&#8217;m not a Ruby developer. Or maybe that&#8217;s just because at the point where I want to write HTML, I want to write stuff that looks like&#8230; HTML.</p>
<p>Moreover, if I have someone whose specialty is HTML and not Ruby, I <strong>really</strong> don&#8217;t want them trying to write such Ruby code. But maybe that&#8217;s just me.</p>
<p><strong>Update 4/27/2010</strong>: John commented to suggest a shorthand for the above in HAML:</p>
<pre style="background-color:#ddd;">
%sandwich{:bread => 'whole wheat', :filling => 'peanut butter and jelly',
:delicious => true}/
</pre>
<p>Certainly this is better than the above (although still inferior to HTML itself IMHO), which by the way came from the official HAML documentation (not me that made that up). I&#8217;m sure they did that to demonstrate how you can override properties with subsequent hashes, etc. But as I said in response to John, the fact that the more complicated form is what&#8217;s found in the HAML documentation will probably lead to more &#8220;newbies&#8221; like me thinking this is the standard way to do HAML. I have the same problem with the thousands of .NET MVC tutorials on the first few pages of Google SERP&#8217;s that tell people the completely wrong way to pass data from the Model to your View. If you document the bad practices enough, the bad practices will become the de facto standard. This is bad. Very bad.</p>
<h4>When writing HTML, I should be writing&#8230; HTML</h4>
<p>Perhaps I should state rather than just imply a bias I have here: if I&#8217;m in the mode of doing front-end (HTML) development (&#8217;cause I know a lot of us wear many different hats from front-end dev to back-end dev in our jobs), I want to think in HTML (not something else) at that point in time. Just like when doing back-end app development, or when building out database schemas, I darn sure don&#8217;t want to care (at that moment) about the eccentricities of cross-browser CSS and box-model support.</p>
<p>I think this kind of role separation (and thus skill separation) makes my job easier. It makes is clearer what I&#8217;m doing at any given point, instead of trying to blur syntactical lines between various technologies in the name of convenience.</p>
<p>I just find I work more effectively when I do only what is necessary for a given task at any one time.</p>
<h4>Templates and Code Logic should not mix</h4>
<p>I feel like this point is almost so self-obvious, I&#8217;m boring you by mentioning it. But yet time after time I see various platforms and frameworks (everything from .NET to Java to PHP to RoR to HAML to everything else in between) making exceptions to these rules, in whole or in part, and allowing (or even encouraging!) you to add some host language logic directly inside your templates.</p>
<p>I guess the logic follows that if you&#8217;re a Ruby developer, and you&#8217;re also tasked with doing front-end (HTML) development, you won&#8217;t mind mixing the two in your mind, using Ruby code logic to assemble your templates and data.</p>
<p>Well, that&#8217;s great until you hire a rock-star HTML/CSS guy to make templates who has zero knowledge of Ruby. I suppose you just hand him a Ruby book and say, &#8220;good luck.&#8221;? Or what about if you decide at some point to change the back-end platform technology you&#8217;re using from Ruby to say Scala or Erlang or PHP or whatever. What becomes of all your templates? Do you keep the Ruby based stuff, or do you ditch them entirely and re-write all your presentation layer as well?</p>
<p>And, btw, how does your development team make decisions effectively about what&#8217;s ok to be Ruby embedded in your templates, and what must be in the controllers? How do you train new developers to your team how to effectively make these decisions quickly right along side all your seasoned developers who&#8217;ve stubbed their toes on those topics for years? How do you decide, philosophically, if logic related to formatting (say a date or currency) is logic that should belong in the templates or in the controllers?</p>
<p>You see, in my opinion, all these questions are harder <strong>because</strong> you&#8217;re using a system that&#8217;s more flexible, more powerful, more complicated than it <em>needs to be</em> or <em>should be</em>. </p>
<p>Just because I <em>can</em> hammer a nail in with a sledge hammer doesn&#8217;t mean that&#8217;s the most effective tool for the job. If I have a little hammer suitable for the task, I think it&#8217;ll be more accurate and efficient to use it than the big sledge hammer. And that&#8217;ll also be true when I hand off the task of nailing things in to a new person who&#8217;s never used the sledge hammer before.</p>
<p><strong>Point:</strong> You don&#8217;t need the power of Ruby to construct templates. If you do, you&#8217;re doing templating wrong &#8212; again, in my opinion. Templating only needs a few simple constructs to be effective. Anything beyond that <em>should be</em> in your Controllers. At least, that&#8217;s what we were all taught in our CS classes when we learned about the proper Object-Oriented approach to MVC and we had it drilled into us that the &#8220;M&#8221;, the &#8220;V&#8221;, and the &#8220;C&#8221; should be separate. How quickly we abandon &#8220;separation&#8221; when it becomes too convenient in the heat of the moment.</p>
<p>I love <a href="http://twitter.com/KentBeck/status/8637230540">this quote I just read</a> on twitter: &#8220;good programmers appreciate the features you put in. expert programmers appreciate the features you left out.&#8221; (via <a href="http://twitter.com/KentBeck">KentBeck</a>)<br />
<h4>Portability</h4>
<p>I&#8217;m also not a fan of having to use more than one templating system. By this, I mean, it is a reality of <strong>most</strong> (even mildly) complex web apps that there are two classes of templating: build-time (on the server) and dynamic (run-time, in the browser, with user input). Of course, various web apps have a different mix, and if you&#8217;re in the small class that is entirely one or the other and always will be, just skip over this point.</p>
<p>However, for the rest of us, almost nothing upsets me more than having to repeat myself. We&#8217;ve all heard DRY (don&#8217;t repeat yourself), but I don&#8217;t just quote that as a nice-to-have, I try hard to live by it in my development career. I am not 100% sure, but I&#8217;d hazard a good guess that it&#8217;s impossible to use the exact same templates (with Ruby logic and all) in both a server environment and a client environment. Moreover, even if there is a port (to JavaScript) of the HAML interpreter that could run in the browser (with alternate templates of course), this is of course two different separate copies of a templating engine that must be independently maintained.</p>
<p>A fundamental &#8220;law&#8221; in Computer Science is that anytime there is more than one copy of something, one copy is always wrong. That&#8217;s where DRY was born from. And it goes for tools as well as content.</p>
<p>You may be saying to yourself, &#8220;wait, that&#8217;s not possible with any templating engine.&#8221; Ahh, but it is! Stay tuned, in a (soon) future blog post here I&#8217;ll be talking about a templating engine I&#8217;ve built which can do just that.</p>
<p>You know what technologies <strong>can and do</strong> run in both contexts? JavaScript and HTML. Anything other than that, and you&#8217;ve almost certainly failed this point. Game over.</p>
<h4>One more thing</h4>
<p>One last point of contention: I am unable to confirm how HAML handles &#8220;compilation&#8221; of templates. If it does so on-the-fly, every time, at run time (since it also has to execute Ruby code to drop in data), then this is more inefficient to convert from shorthand code to raw HTML each time.</p>
<p>If however it has some sort of two-pass compilation, where at build time you compile the shorthand HAML to raw HTML, and then at run-time you execute the embedded Ruby to drop in data, then this is probably a better approach efficiency wise. </p>
<p>Still, the point remains, that type of technique is important for performance, and it&#8217;s not very common amongst most templating solutions.</p>
<h2>Enough already</h2>
<p>OK, that&#8217;s enough ranting for one post. Again, the purpose here was to lay out what I don&#8217;t like about HAML. The underyling frustrations however are not specific to HAML but are true of many, many templating solutions. So up coming will be posts where I try to be more constructive and offer some solutions. Hopefully you&#8217;ll find this dialogue helpful. That is of course if you haven&#8217;t already written me off as being a crazy, eccentric, opinionated technology bigot.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.getify.com/2010/02/why-i-dont-like-haml/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>

<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Content Delivery Network via getiblog.2static.it

Served from: blog.getify.com @ 2010-09-07 21:02:54 -->