Rey Bango

Web developer, honey badger

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>

Category: AJAX, JavaScript, jQuery

Tagged:

19 Responses

  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!

  2. IMO jquery templates will be great with server-side templates (smarty or similiar). Standalone Javascript templates… possible, but why? Have no idea.

    • Rey Bango says:

      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. jQuery JavaScript Templates Tutorial: Inline Expressions and Code Blocks – Rey Bango…

    Thank you for submitting this cool story – Trackback from DotNetShoutout…

  4. Adrian Adkison says:

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

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

  8. Parashuram says:

    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…

  9. [...] jQuery JavaScript Templates Tutorial: Inline Expressions and Code Blocks (Rey Bango) [...]

  10. Paul says:

    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.

  11. Denny says:

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

  12. Denny says:

    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

    • Denny says:

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

  13. Brian says:

    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?

Sponsors



Learn JavaScript!

What to Read to Get Up to Speed in JavaScript.

The best books & blogs for learning JavaScript development. Broken down by experience levels!


My BIG LIST of JavaScript, CSS & HTML Development Tools, Libraries, Projects, and Books.

Constantly updated with the latest and greatest tools. Check it out!

Categories

Rey Bango is Stephen Fry proof thanks to caching by WP Super Cache