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:

[code language=”js”]
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"] }
];
[/code]

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:

[code language=”js”]
<script id="clientTemplate" type="text/html">
<p><li>${ first + " " + last }</li></p>
</script>
[/code]

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:

[code language=”js”]
{{if (age > 30)}}veteran coder!{{else}}rising star!{{/if}}
[/code]

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:

[code language=”js”]
<script id="clientTemplate" type="text/html">
<p><li>${ first + " " + last + " is a " }{{if (age > 30)}}veteran coder!{{else}}rising star!{{/if}}</li> </p>
</script>
[/code]

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:

[code language=”js”]
{{if (age > 20 && age < 30 || age == 42)}}rising star!{{else}}veteran coder!{{/if}}
[/code]

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:

[code language=”js”]
<!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>
[/code]

Rey Bango

19 Comments

  1. 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.

  2. 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.

  3. Pingback: DotNetShoutout
  4. I have been itching to integrate this into my project. Is there any official documentation or any idea when there will be?

  5. 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.

  6. 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!

  7. 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.

  8. 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}}

  9. 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().

  10. Dumping tags into the page sorta gives me the heebie jeebies. Is there a way to link to a template document externally a la stylesheets?

Comments are closed.