How to escape inline JavaScript blocks in Velocity Templates

Inline JavaScript blocks can be escaped in Velocity templates to avoid conflicts with the $ variable often used in jQuery code. This is done with the don’t parse directive:

#[[ … ]]#

For example, in a Global Template :

<!DOCTYPE html>
<html>
<head>
<title>#field('mytitle')</title>
<script>
#[[
$( document ).ready(function() {
    console.log( "ready!" );
});
]]#
</script>
...

When the template is assembled, Velocity will ignore the JavaScript block. This will make the page assemble quicker, and will also prevent Velocity from getting confused when it sees the $ symbol in the JavaScript code.

3 Likes