Sree Ram Sree Ram - 10 months ago 91
HTML Question

Chrome Uncaught SyntaxError: Unexpected token < Jinja Template

I am using jinja templates. Calling a function with an object as the parameter.
This is the caller.

<input class="btn btn-primary center-block" onclick=execute( {{ x }} ) type="submit" id= 'receive-btn' value="Receive" >

When the code is actually called this is how the object is getting passed.

<input class="btn btn-primary center-block" onclick=execute((&lt;Orderitem u&#39;Lenovo Vibe K5 (Gold, 16GB)&#39;&gt;, datetime.datetime(2016, 9, 12, 16, 26, 47), u&#39; 402-7679899-5460354&#39;, u&#39;Lenovo Vibe K5 (Gold, 16GB)&#39;, 7000.0, 0.0, 1L, u&#39;9963802143&#39;, u&#39;nagaraju&#39;, 0.0, 0.0, UUID(&#39;377245de-ebaa-4fa9-ad70-8fa28ad602ae&#39;))) type="submit" id= 'receive-btn' value="Receive" >

The object seems ok to me, but I get his error:

Uncaught SyntaxError: Unexpected token <

Any reason why this happens?
I am new to both Javascript and Jinja. In general how to pass this object to a javascript function?

Answer Source

It looks like you are trying to pass a string to the execute function in JavaScript.

Strings literals, in JavaScript, must be surrounded with " or '.

Since you haven't done that, the first character of your data (<) is treated as a less than operator, which isn't allowed as the first character inside the () that call a function.

Quote your strings.

(You also need to quote your HTML attribute values when they contain spaces and certain other characters).

onclick="execute(&quot;{{ x }}&quot;)"

NB: This will break if your data ever includes " characters. Look at converting the x to JSON before putting it into the template.