Jul 14, 2010
jQuery JavaScript Templates Tutorial: Inline Expressions and Code Blocks
So far in my series on jQuery JavaScript Templating, I’ve showed how to create a basic jQuery JavaScript template and then nest templates for increased layout flexibility and maintainability. If you haven’t read those two posts, I highly recommend you do so you can understand the concepts below.
Now, let’s dive into two other techniques available in the Microsoft jQuery Templates plugin; inline expressions and code blocks.
Inline Expressions
Being able to use a template to create a succinct layout is very powerful but without the ability to manipulate the data that’s being rendered, you’d probably find templates a lot less useful. That’s where inline expressions come in. Inline expressions allow you to use common JavaScript expressions to effect a change in the way your data is rendered. Using a slightly modified version of the data from my last tutorial, I can show you what I mean. Here’s the data:
var clientData = [
{ first: "Rey", last: "Bango", age: 42, id: 1, phone: [ "954-600-1234", "954-355-5555" ] },
{ first: "Mark", last: "Goldberg", age: 51, id: 2, phone: ["954-600-1234", "954-355-5555"] },
{ first: "Jen", last: "Statford", age: "25", id: 3, phone: ["954-600-1234", "954-355-5555"] }
];
What I did was break out the “name” attribute into “first” and “last” name fields. Now, say I wanted to render the full name in my template. I would use the following inline expression to do so:
<script id="clientTemplate" type="text/html">
<p><li>${ first + " " + last }</li></p>
</script>
Which gives me the following result:
Notice that I’m using the standard JavaScript “+” operator to concatenate the two data attributes together to form my final output. JavaScript developers should immediately be able to understand the code here and see how flexible this option is.
Code Blocks
Now, while inline expressions are certainly powerful, the ability to affect the data via code blocks is even more important because it allows you to specify conditional statements that can be used to determine what type of and when data will be represented. Let’s say that based on the age of a client, I want to show some text next to their name. I’ll use the following code block:
{{if (age > 30)}}veteran coder!{{else}}rising star!{{/if}}
This code block allows me to specify a conditional statement that allows me to create a nice descriptor based on the person’s age. The key is the “{{if..else}}” custom tag that’s been incorporated into the template plugin that allows you to specify conditional statements.
Here’s what the template would look like:
<script id="clientTemplate" type="text/html">
<p><li>${ first + " " + last + " is a " }{{if (age > 30)}}veteran coder!{{else}}rising star!{{/if}}</li> </p>
</script>
which generates the following results:
And again, the cool thing is that the syntax for the expressions use standard JavaScript operators so I can do something like this as well:
{{if (age > 20 && age < 30 || age == 42)}}rising star!{{else}}veteran coder!{{/if}}
The thing to stress here is that using inline expressions and code blocks together can give you a tremendous amount of control over how you control you data. You have the flexibility you’d expect by using JavaScript but in a manner that is easily readable and maintainable.
Here’s the final code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="robots" content="noindex" />
<title>Template Test</title>
<script src="http://code.jquery.com/jquery.min.js" type="text/javascript"></script>
<script src="jquery.tmpl.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
var clientData = [
{ first: "Rey", last: "Bango", age: 42, id: 1, phone: [ "954-600-1234", "954-355-5555" ] },
{ first: "Mark", last: "Goldberg", age: 51, id: 2, phone: ["954-600-1234", "954-355-5555"] },
{ first: "Jen", last: "Statford", age: "25", id: 3, phone: ["954-600-1234", "954-355-5555"] }
];
$("#clientTemplate").tmpl(clientData).appendTo("div");
});
</script>
<script id="clientTemplate" type="text/html">
<p><li>${ first + " " + last + " is a " }{{if (age > 20 && age < 30 || age == 42)}}rising star!{{else}}veteran coder!{{/if}}</li> </p>
</script>
</head>
<body>
<div></div>
</body>
</html>
Related posts:
- jQuery JavaScript Templates Tutorial: Nesting Templates In my last post, I presented an intro to how...
- Not Using jQuery JavaScript Templates? You’re Really Missing Out. In preparation for my upcoming talk on jQuery Templates, I’ve...
- I’m Presenting on jQuery Templates at ThinkVitamin’s jQuery Online Conference This coming Monday (7/12/2010), I’ll be one of the speakers...
- The Source Code for my Twitter Demo from the Think Vitamin jQuery Online Conference Templating Presentation I just finished my presentation at Think Vitamin’s jQuery Online...
- Generic Activity Indicator for Ajax Requests Over the weekend I was fiddling was some code to...
Related posts brought to you by Yet Another Related Posts Plugin.


AIM: iamreybango

Once again -fracking cool. I know I mentioned this in the other post, but you got to get the official page updated with your examples. Your posts are really “selling” this plugin!
Thanks Ray! I’ll talk to the team. BTW, I added a new plugin to my blog to allow you to subscribe to notifications.
IMO jquery templates will be great with server-side templates (smarty or similiar). Standalone Javascript templates… possible, but why? Have no idea.
They’re useful in web applications with rich UIs where you need to do a lot of DOM manipulation. It makes it easier to manage that.
…not to mention if you’re ever doing ajax calls to a remote resource, and bang your head against the same-origin policy of cross-domain calls. Then you’re stuck with hacks, or jsonp data calls, in which case client side templates (or their equivalent) are very handy.
jQuery JavaScript Templates Tutorial: Inline Expressions and Code Blocks – Rey Bango…
Thank you for submitting this cool story – Trackback from DotNetShoutout…
I have been itching to integrate this into my project. Is there any official documentation or any idea when there will be?
Rey, thanks for this series of posts. They are very useful, and one day I will jump onboard the tmpl train…
But not yet:
* MS (or someone) needs to provide syntax highlighting for html inside script blocks in Visual Studio.
* How do you debug tmpl templates? Debugging dynamically generated javascript is bad enough, debugging javascript inside an html template that is driven by json and evaluated using a complex regular expression… Now you’re nearing brainfcuk level complexity.
For now I would advocate keeping templates simple, and keep the logic in the main javascript code.
[...] jQuery JavaScript Templates Tutorial: Inline Expressions and Code Blocks – Rey Bango continues his series looking at templating in JavaScript and jQuery with a look at the inline expressions and code blocks features provided in the Microsoft jQuery Template plugin. [...]
I love this plug-in. I *hated* passing back html markup, or creating an HTML structure out of jQuery code, or even creating a hidden HTML structure that I cloned through jQuery.. it was all very ugly. Templating is neat, clean and powerful!
Thanks a ton!
Hey Rey,
Here are your examples, in a playgroud kind of way – http://bit.ly/czwQJe
Covers all the four examples that you covered in your blog…
[...] jQuery JavaScript Templates Tutorial: Inline Expressions and Code Blocks (Rey Bango) [...]
Loved this so much had to try it…but can’t get this example to work; syntax error in jquery.tmpl.js…
Anyone point out what I’m doing wrong?
Thanks.
@Paul: If you can put up a demo link, I can check it out.
Thanks for the article, it helps a lot! I have one question, is it possible to have another if statement within if statement? I tried but it seems doesn’t work.
{{if (foo && foo.length > 0)}}
{{if(foo === ‘true’)}}
{{/if}}
Thanks for the article, it helps a lot! I have one question, is it possible to have if statement within another if statement? I tried but it doesn’t work.
{{if (foo && foo.length > 0)}}
{{if(foo === ‘a’)}}
// do something
{{ else }}
// do something
{{/if}}
{{/if}}
Edit: sorry for the double post, I have press the wrong button. Can you remove the previous post? Thanks
sorry, I made a mistake, its actually work. It doesn’t work before because I try to run {{if(foo.toLowerCase() === ‘a’)}} in the inner if statement. It doesn’t accept .toLowerCase().