jQote – client-side templating
jQote2 has been released. Please consider upgrading now!!! Click here for a quick summary of what’s new and what’s changed.
See the jQote API reference.
Version 1.1.0 now gives you the possibility of changing the tag character to something else than <% and %>. Please referr to the jQote API reference to see how to do it.
So, let’s get started writing down a basic template:
<script type="text/html" id="template"> <![CDATA[ <p class="greetings"> Hello <%= this.name %>, how are you doing? May I offer you <% this.is_starving() ? %> some tasty peasant? <% : %> a refreshing Singha? <% ; %> </p> ]]> </script>
This well-mannered code snippet – though it may not seem like much – shows some very special markup, namely
<%= expression %> and
<% statement %>, respectively (please notice the extra ‘=’ sign on the first one).
<%= %> tag whenever you want to directly echo a variable’s value (you may as well call a function or use any other expression, as long as it returns a string).
Pretty self-explanatory so far, hu? But what’s with all that
<script type="text/html"> and
<![CDATA[ ... ]]> shmoo, you ask? Well let’s cite John Resig here:
“Embedding scripts in your page that have a unknown content-type (such is the case here – the browser doesn’t know how to execute a text/html script) are simply ignored by the browser – and by search engines and screenreaders. It’s a perfect cloaking device for sneaking templates into your page. [...]“
Good news, that is we will be able to put our template code right into our HMTL source files and it won’t show up anywhere but in the sources (btw. thanks to the usage of CDATA it’s perfectly valid markup).
Now for the final part of our little example we’ll need some basic scripting to induce the conversion:
That’s it, there’s nothing more to it than calling jQote on our template and providing it with some data object to get things started. jQote really is fun to use and cuts down on the time spent trying to inject arbitrary data into your sites. You’ll learn to love it pretty fast, I promise! Give it a try.
One final word: I’d like to thank John Resig for bringing this up. You rock, dude.