AJAX - The Complete Reference

(avery) #1

PART II


Chapter 9: Site and Application Architecture with Ajax 441


<!-- Template-Begin URL=’rating-Ajax.tpl’ -->
<h3>Thanks for voting!</h3>
<p>Your rating: {$userrating}. <br />
Average rating: {$avgrating}.<br />
Total votes: {$totalvotes}. <br />
</p>
<!-- Template-End -->
<!-- Template-Begin URL=’thankyou-Ajax.tpl’ -->
<h2>Thank you for registering {$username}</h2>
<p>Contact technical support at 555-1212</p>
<!-- Template-End -->

Comments are used as the delimiters because they can be parsed out quite easily.
Then the cache() method is called, adding each URL indicated because the AjaxTCR
.template.cache() method also allows you to cache template strings using a URL value
as key. For example:

AjaxTCR.template.cache("templates/hello.tpl","<h1>Hello {$name}!</h1>");

would cache the small template as the URL value specified. Of course, it doesn’t put it at the
URL in question; it is just associating it with that key in the local template cache.

Templates in Strings
Let’s continue with the sample JSON response to see what other approaches can be taken
with client-side templates. First, consider that there could be a response packet with the
template included in the templateText property.

{"average":3.37,"rating":"4","votes":475, "templateURL" : "", "templateText" :
"{if $downgradeversion}{include file=\"ratingHeader.tpl\"}{/if} <h3>Thanks for
voting!</h3> <p>Your rating: {$rating}. <br /> Average rating: {$average}.<br />
Total votes: {$votes}. <br /></p> {if $downgradeversion}{include file=\
"ratingFooter.tpl\"}{/if}" }

Of course, there must be a way to translate this template string and values into rendered
markup. So we introduce another method, AjaxTCR.template.translateString(template
string, data). In the case of specifying the template and templateRender property in the
request options, the method is used automatically, but if you want to render templates yourself
from strings, it can be done with this method. Clearly it is advantageous to send the template
with the response and avoid a second request for the template, but you may think there is little
communication savings here, byte wise, if the same task is performed again. This is where the
URL comes in when the string is specified. If the templateURL and templateText are both
used, the text will be cached as before, so we can piggyback the template on the first response
and then avoid sending it down again later on. Of course, you may need to write some server-
side logic to determine that the necessary client template has already been sent.

Server Rendering
Now there are two more cases with templates we could consider, but they are much less
likely and less useful than the previous examples as we are focused on the client. The
template could be set to a URL and then indicated that it should be rendered on the server.
We introduce the convention that the value templateURL=request.template where the
Free download pdf