Velocity - How to avoid ParseErrorException when using jQuery?

Michael picture Michael · Jul 26, 2011 · Viewed 11.7k times · Source

I'm trying to add a jQuery post to some JavaScript on a web page. The entire page is built up of several Velocity templates. Everything has been fine until I've tried to add the jQuery post, now I get:

org.apache.velocity.exception.ParseErrorException: Encountered "," at line 282, column 24 of /WEB-INF/velocity/www/comments.vm
Was expecting one of:
    "(" ...
    <RPAREN> ...
    <ESCAPE_DIRECTIVE> ...
~~~snip~~~

Line 282 is $.post(... and column 24 appears to be the first "," character. Initially I had the JSON on this line, but I moved it up (to the var myJSONObject ... line)as I thought the error related to invalid JSON (tabs at the start of the line gave a misleading column number).

var myJSONObject = {"body": "", "action": "postcomment", "submitted": "true", "ajax": "true"};
myJSONObject.body = $("body").val();
$.post("$!{articleurl}", myJSONObject, function(result){            
    btn.textContent='Comment sent successfully.';  
});

Minor Update

I changed the following lines:

var url = "$articleurl";

$.post(url, myJSONObject, function(result){
~~~snip~~~

The parse exception still focuses on the first ",". I'm assuming the issue is that Velocity thinks it should be able to resolve $.post - when in fact, it's jQuery. I've used jQuery in other Velocity VM templates without any problem. Is there a way to get Velocity to ignore certain lines / statements when parsing?


Update 2

I found this link about escaping references in Velocity, but it does not resolve my issue. Adding a "\" before $.post gives me the exact same error, but the column is one extra, because of the character added at the start of the line.

Answer

serg picture serg · Jul 26, 2011

You can wrap your javascript with #[[ ... ]]# which tells Velocity to not parse the enclosed block (new in Velocity 1.7)

#[[ 
<script>
    ...
</script>
]]#