Client-side templates have become a vital component of AJAX-driven websites. The web is undoubtedly trending towards sites that load content dynamically after the page loads, rather than all at once in the initial page request. This pattern allows web pages to become lighter and more responsive, which translates to a better experience for the user. However, the conventional server side templating and databinding techniques that web developers typically use aren’t as effective anymore. That is why there are so many JavaScript template solutions that have popped up in recent years:
- ASP.NET Ajax 4
- ExtJs and XTemplate
- jQuery Plugins like Chain.js, jTemplates, jBind, etc.
- Google Closure Templates
Google’s Closure Templates is the new kid on the block, and the subject of this article. One might wonder: Why do we need yet another JavaScript templating solution? The main advantage that sets Closure Templates apart from the other libraries is the included compiler. Other templating solutions either parse a string of special template syntax, or traverse through actual html elements with special markup or extra classes. When making light use of client-side templates, these solutions can work very well. But, as you start to build applications with extremely large datasets and complex templating, then performance starts to become an issue. These scenarios are where Closure templates begin to shine. Instead of directly using the template that you write, you run it through the compiler to output JavaScript functions that you can use in your code. This process is advantageous on two levels; the first is that the JavaScript functions outputted from the compiler are going to be optimized and extremely fast. Secondly, the compiler can also create server side compatible templates as well, so that you can write your templates once and be able to use them either in JavaScript or in server-side code. Unfortunately, the current version of the compiler can only generate Java code, and there is no option for .NET languages such as C#. This is a bummer for .NET developers, but even without C# templates, there is still great value in lightning-fast, compiled JavaScript templates.
Creating your first Closure Template in Visual Studio 2010
Let’s start with a new ASP.NET MVC Project:

You can create a Web Application project if you are more comfortable with that type of project structure. Because we will be dealing with just JavaScript, it shouldn’t matter.
After creating a project, download the compiler and JavaScript utility library. Extract the zip file, and copy both SoyToJsSrcCompiler.jar and soyutils.js to your templates directory:

You will see in the screenshot above that I have changed the Build Action of SoyToJsSrcCompiler.jar to “None”, and Copy to Output Directory is set to “Do not copy”. This ensures that the compiler is not compiled into the dll, and the file is not copied to the output folder. The latter is especially useful when using Visual Studio’s publish feature, because the compiler is not necessary when deploying your website.
Now that we have the required files in place, let’s go ahead and create a soy template file, example.soy. This is the file that will contain one or more templates using Closure’s template syntax. After creating a template in this file, we will then use the compiler to generate a JavaScript representation of the template that we will reference in our html page. Every soy file should have the three following components, in the following order:
- A namespace declaration.
- One or more template definitions.
- A newline at the end of the file.
Go ahead and enter the following example template in your example.soy file:
{namespace closure.examples}
/**
* Says hello to a person.
* @param name The name of the person to say hello to.
*/
{template .helloName}
Hello {$name}!
{/template}
Make sure that your soy file is encoded as ANSI, rather than UTF-8. Even though Google says UTF-8 should be supported, in Windows 7 x64 (and maybe other Windows operating systems and versions) this is currently not the case. And if you create a file within Visual Studio, it will encode the file as UTF-8 and you will get the following exception when compiling a template:
Exception in thread "main" com.google.template.soy.base.SoySyntaxException: In file example.soy: Tag 'namespace' not at start of line.

If you are unsure that your file is saved with the proper encoding, just open it up in notepad, and select File > Save As to see or change the encoding.
After we’ve included the necessary files in our project, it’s time to make compiling templates a little more user-friendly. The jar file is pretty annoying to call from the command line and manually change the parameters for each of your different soy files. Visual Studio has a perfect solution for this, and it’s called External Tools. This feature allows you to set up a VS menu item and seamlessly run commands from the IDE with just the press of a button. To do this, first click on Tools > External Tools from the menu:

From here, you can create a new menu item with the following parameters:
Title: Compile Closure Template
Command: C:Program Files (x86)Javajre6binjava.exe
Arguments: -jar "$(ItemDir)SoyToJsSrcCompiler.jar" --outputPathFormat $(ItemFileName).js $(ItemFileName)$(ItemExt)
Initial Directory: $(ItemDir)
(Thanks to Tj Stewart for this tip)
Note that your Command entry may differ, depending on where your java installation resides on your computer. Here is what it looks like:

Once you have this setup, compiling your soy templates is as simple as selecting the soy file in solution explorer and pressing the “Compile Closure Template” button in the Tools menu:

When you attempt to compile a template, make sure to have your output window open. If there are any exceptions that occur during the compilation, this is where they will be displayed. If the compilation was successful, you should now have a new example.js file in the Templates directory. Note that it won’t be added to the project automatically, so you’ll have to add it yourself. Subsequent compiles for the same soy file will only require this step once.
Now let’s create a page to utilize the new template, and call it example.html. We could create an MVC view, but it really isn’t necessary since we are only dealing with JavaScript:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <script type="text/javascript" src="Scripts/Templates/soyutils.js"></script> <script type="text/javascript" src="Scripts/Templates/example.js"></script> <script type="text/javascript"> $(function () { $('#wrapper').html(closure.examples.helloName({ name: 'Sam' })); }); </script> </head> <body> <div id="wrapper"></div> </body> </html>
I’m using a little jQuery to make my life easier here, and notice that I am passing JSON with the Closure template parameters as the properties of the object. Your result should look something like this:

In summary, Google Closure Templates provide a scalable solution to client side templating by providing an understandable syntax in the form of soy files, with the ability to compile those templates into fast and efficient JavaScript functions that you can use in your pages. Even though there is no current support for reusing Closure templates in C#, there is still value in utilizing this solution in a Visual Studio project, especially when the External Tools feature makes compilations so easy and convenient.
I hope this article serves as a starting point to getting up and running in Visual Studio 2010. In future articles, I will be delving into more complex examples and explanations of Closure Templates in real-world scenarios.
Pingback: Using Google Closure Templates with ASP.NET MVC in Visual Studio 2010 - Sam Mueller
Pingback: Using Google Closure Templates with ASP.NET MVC in Visual Studio 2010 | I love .NET!
Pingback: ASP.NET MVC Archived Blog Posts, Page 1
Any plans on showing real-world examples?
Frank, a blog post is coming on Closure Templates being used in far more exotic scenarios. Stay tuned.
Very helpful
Thanks
Sam, I know why UTF-8 is not working for you. The Closure Templates docs mention this relevant note:
“Note: Windows users should note that the template compiler does not accept UTF-8 with a BOM (byte-order mark). Please save your Soy files as UTF-8 without any BOM.”