Saturday, September 11, 2010

When to use single or double quotes in Velocity

Did you see that episode of the Simpsons where Bart writes on the blackboard: "I shall not use single quotes around variable names in Velocity." No? *Sigh.* Neither did I, which is why I write this post. It is my penance given in the hope that I will not make this mistake a fourth time, or at least recognise the mistake immediately by, say, the tenth time.

In Velocity, single and double quotes are similar to Bash scripting: variable references will be evaluated in double quotes, but not single quotes. For example, if you have #set( $name = "Rob" ) then "My name is $name" will output My name is Rob but 'My name is $name' will output My name is $name.

I think the best practice is to use double quotes by default and use single quotes only when you specifically want to avoid evaluating the contents of the string.

"I shall not use single quotes around variable names in Velocity."
"I shall not use single quotes around variable names in Velocity."
"I shall not use single quotes around variable names in Velocity."
"I shall not use single quotes around variable names in Velocity."
"I shall not use single quotes around variable names in Velocity."
"I shall not use single quotes around variable names in Velocity."
"I shall not use single quotes around variable names in Velocity."
"I shall not use single quotes around variable names in Velocity."
"I shall not use single quotes around variable names in Velocity."
"I shall not use single quotes around variable names in Velocity."

Read more about the quoting rules and more in Apache's User Guide for Velocity.

My dotCMS notes.