Atlassian, Interesting

Friends don’t let friends write Javascript in Velocity templates.

The Problem

Very recently I was writing an Atlassian plugin for JIRA. I was trying to add some Javascript directly to a Velocity template instead of including it from its own file (I know; naughty me). But the problem that I was seeing is that trying to use the JQuery ajax function that Atlassian wraps in AUI (Atlassian User Interface) was coming out incorrectly. In-fact this:


Was being converted from the template into HTML to look like like this:


And obviously that is not even valid Javascript and Google Chrome spat out some parsing errors in the console.

The Cause

In hindsight the problem in obvious. In velocity templates the ‘$’ symbol is very special: it is what velocity uses to refer to variables. Velocity is used to seeing ‘$object.getSomeMethod’ so when it saw ‘$.’ it just said I have no object that matches ” (empty string) and therefore I will render ‘$.’ as the empty string. Which resulted in us not getting our dollar symbol back and Javascript errors popping up.

The Solution

The best solution is to simply not write Javascript in your templates (please) doing that is just not nice and you should be encapsulating your CSS and Javascript into separate resource files by default. If you are not then please start doing that now. Look at the documentation and examples on how to do that in Atlassian Plugins.

However, I know that there are going to be some of you in the crowd that are going to say “But what if I really really really do want to write Javascript in my template?” Well for those people I give you this post from StackOverflow:

In Velocity 1.7b1 new syntax #[[this is included in output but not parsed]]# was introduced:
    $(document).ready(function() {

I hope this helps you fix any problems you may have been having and also to have convinced you to stop using Javascript in Velocity templates.