AJAX - The Complete Reference

(avery) #1

434 Part II: Developing an Ajax Library^


<title>Voting Results for downgraded version</title>
</head>
<body>
<h3>Downgrade Version</h3>

and ratingFooter.tpl included:

</body>
</html>

If we designed the presentation layer of the rating system in this manner, it can use the
same primary template file for both cases and just choose where to render it, client-side in
the case of an Ajax response and server-side in the case of a downgrade-style response.

Client-Side Templates


To explore client-side rendering, we add a template facility to our library: AjaxTCR.template.
Syntax-wise the template language is going to mimic the server-side template system so
that templates can be rendered either client side or server side. We will use a mere subset of
the Smarty environment, since our goal is to explore the architectural concept not building
out a whole new templating system. However, after you explore the approach presented,
you’ll probably agree that the elegance that it provides will encourage many client- and
server-side template systems to begin using similar syntax.

Syntax Overview
The basic syntax of our template language is described briefly here. First of all, the constructs
will be wrapped in curly braces { }. Our primary goal of the template is data substitution.
Replacements are indicated with a $varname, where varname corresponds to the value we
want to replace the token with. As an example with a JSON value like:

{"greeting" : "Hola" , "myname" : "Thomas" }

applied to a template containing:

{$greeting} my name is {$myname}.

It would render:

Hola my name is Thomas.

Basic selection can be accomplished with the {if} construct. Here if the condition has
a true value in it, the word gets rendered; if false, or if the string value in the specified
variable is empty, no markup is output.

{if $fancy}
<span style="color:red;">Fancy!</span>
{/if}

An {else} clause can be added like so:

{if $fancy}
<span style="color:red;">Fancy!</span>
Free download pdf