Escape quotes in Javascript/Chameleon template - javascript

I am trying to pass a python dictionary from a chameleon template to a javascript function. But since the dictionary contains single quotes or ' which need to be escaped I get an error in firebug that says : SyntaxError: missing ) after argument list.
My code looks like this:
<div id = "divsfp">
<input type="button" id="sfp" value="SFP"
onclick="get_sfp('${dict_value}')"></input></div>
Where dict_value is a python dictionary. How can I escpae ' in chameleon template before passing the data or in Javascript function itself?

You need to JSON encode the dictionary. You don't then need to put quotes around the dictionary, and JavaScript will see it as a JavaScript object.

Use double-quotes, encoded as &quot:
onclick="get_sfp("${dict_value}")"
Chameleon will escape any double-quotes in dict_value.

You can try this, if this helps
"get_sfp('"+${dict_value}+"')"
Also from your implementation it seems that the dict_value is the variable you already know. So whats the problem accessing it from the get_sfp function.
Sorry couldn't comment as I still don't have that privilege.

Related

How to Use ES6 Template Literals in Freemarker? [duplicate]

I'm trying to use Freemarker in conjunction with jQuery Templates.
Both frameworks use dollar sign/curly brackets to identify expressions for substitution (or as they're called in freemarker, "interpolations") , e.g. ${person.name} .
So when I define a jQuery Template with expressions in that syntax, Freemarker tries to interpret them (and fails).
I've tried various combinations of escaping the ${ sequence to pass it through Freemarker to no avail - \${, \$\{, $\{, etc.
Inserting a freemarker comment in between the dollar and the curly (e.g. $<#-- -->{expression}) DOES work - but I'm looking for a more concise and elegant solution.
Is there a simpler way to get a Freemarker template to output the character sequence ${?
This should print ${person.name}:
${r"${person.name}"}
From the freemarker docs
A special kind of string literals is the raw string literals. In raw string literals, backslash and ${ have no special meaning, they are considered as plain characters. To indicate that a string literal is a raw string literal, you have to put an r directly before the opening quotation mark or apostrophe-quote
For longer sections without FreeMarker markup, use <#noparse>...</#noparse>.
Starting with FreeMarker 2.3.28, configure FreeMarker to use square bracket syntax ([=exp]) instead of brace syntax (${exp}) by setting the interpolation_syntax configuration option to square_bracket.
Note that unlike the tag syntax, the interpolation syntax cannot be specified inside the template. Changing the interpolation syntax requires calling the Java API:
Configuration cfg;
// ...
cfg.setInterpolationSyntax(SQUARE_BRACKET_INTERPOLATION_SYNTAX);
Then FreeMarker will consider ${exp} to be static text.
Do not confuse interpolation syntax with tag syntax, which also can have square_bracket value, but is independent of the interpolation syntax.
When using FreeMarker-based file PreProcessor (FMPP), either configure the setting via config.fmpp or on the command-line, such as:
fmpp --verbose --interpolation-syntax squareBracket ...
This will call the appropriate Java API prior to processing the file.
See also:
https://freemarker.apache.org/docs/dgui_misc_alternativesyntax.html
http://fmpp.sourceforge.net/settings.html#templateSyntax
Another option is to use #include with parse=false option. That is, put your jQuery Templates into the separate include page and use parse=false so that freemarker doesn't try and parse it.
This would be a good option when the templates are larger and contain double quotes.
I had to spent some time to figure out the following scenarios to escape ${expression} -
In Freemarker assignment:
<#assign var = r"${expression}">
In html attribute:
Some link
In Freemarker concatenation:
<#assign x = "something&"+r"${expression}"/>
If ${ is your only problem, then you could use the alternate syntax in the jQuery Templates plugin like this: {{= person.name}}
Maybe a little cleaner than escaping it.
Did you try $$?
I found from the Freemarker manual that ${r"${person.name}"} will print out ${person.name} without attempting to render it.
Perhaps you should also take a look at Freemarker escaping freemarker
I can confirm that the
${r"${item.id}"}
is the correct way as an example.
So I kinda full example will look like
<span> Remove </span>
and the output will be :
<span> Remove </span>
In the case when you want to use non-raw strings so that you can escape double quotes, apostrophes, etc, you can do the following:
Imagine that you want to use the string ${Hello}-"My friend's friend" inside of a string. You cannot do that with raw strings. What I have used that works is:
${"\x0024{Hello}-\"My friend's friend\""}
I have not escaped the apostrophe since I used double quotes.

Pass image url from variable to html in javascript

In my script, text(message.image) returns a dynamic URL path of an image. What would be the correct statement in a javascript?
This fails:
$('<div/>').'<img src=\"'.text(message.image).'\">'.appendTo($('#msgDiv'));
The real answer is:
$('<div><img src="'+message.image+'"/></div>').appendTo($('#msgDiv'));
You have a couple syntactic errata in your code snippet:
You can't access a property with a string like you do.
Concatenation of strings is not with a dot but with a plus.
You are trying to execute text() on a string, not on the div.
I think you're missing (),+,append method and escaping " incorrectly, try with this:
$('<div/>').append('<img src="' + text(message.image) + '"/>').appendTo($('#msgDiv'));
Hope this helps,
I think you have a problem because you're using (double)quote badly
You escape the double quote but you're using simplequote. Try that :
$('<div/>').'<img src=\''.text(message.image).'\'>'.appendTo($('#msgDiv'));
And are you sure concerning the syntax $('').'SOME HTML CODE' ?
You are missing ( and ) there.
Also, you dont need to escape double quotes since you are using single quotes outside.
Try this:
$('<div/>').('<img src="'+text(message.image)+'">').appendTo($('#msgDiv'));

Escaping quotation marks in PHP for JavaScript function argument

I'm having trouble escaping a quotation mark in PHP.
I have a table of products and each row has an onclick function, with the name of the product as the argument.
The name contains the length which is measured in inches, so the name contains a quotation mark. I wrapped an addslashes() around the string. This adds a backslash before the quotation mark but for some reason it doesn't seem to escape the character!
Here's a snippet of my code:
<?$desc1 = addslashes($row['Desc1']);?>
<tr class='tableRow' onclick='afterProductSelection("<?=$desc1?>")'>
<td><?=$row['Desc1']?></td>
When I inspect element in Google Chrome, the colour of the syntax indicates that this has not been escaped, clicking on it gives me a syntax error.
Probably something simple that I'm missing. Hope you can help!
There are a lot of different cases where you need to escape a string. addslashes() is the wrong answer to pretty much all of them.
The addslashes() function is an obsolete hang-over from PHP's early days; it is not suitable for any escaping. Don't use it. Ever. For anything.
In your particular case, since you're creating Javascript data from PHP, use json_encode().
json_encode() will take a PHP variable (whether it's a string, array, object or whatever) and convert it into a JSON string. A JSON string is basically fully escaped Javascript variable, including the quotes around your strings, etc. This is what you need to do.
The addslashes() function is an obsolete hang-over from PHP's early days; it is not suitable for any escaping. Don't use it. Ever. For anything. -Spudley
I think the function you're looking for is htmlentities()
<?=htmlentities($desc1, ENT_QUOTES)?>
http://ca1.php.net/htmlentities
You are generating a JavaScript string encoded as HTML so you need to encode twice:
Use json_encode() to generate the string
Use htmlspecialchars() to encode as HTML
Use json_encode to output variables from the backend in JavaScript:
<tr onclick='afterProductSelection(<? print json_encode($desc1); ?>)'>
N.B.: For string output there is no need for extra quotes.

javascript syntax for passing variables to function

I have a JavaScript hyperlink that is not passing variable to function, undoubtedly due to syntax. Can someone please spot error.
jsfiddle: http://jsfiddle.net/kSVVX/
js
function follow(id){
alert(id);
}
html
<a href='javascript:void(0);' onclick= 'follow('1');'><img src='images/test.gif' border=0 alt='follow'></a>
Note: The reason that I am using all apostrophes is that this link is actually getting echoed from php where a long string is enclosed in quote marks (as certain things in the string must be in apostrophes.) I have a feeling this is source of problem, but have not succeeded in solving it by changing punctuation around.
Thanks for any suggestions.
You are using ' characters to delimit your JavaScript string and the HTML attribute value it is embedded in.
This results in:
onclick= 'follow('
Either:
Avoid intrinsic event attributes (which you should be doing anyway, unobtrusive JavaScript is recommended).
Use different characters to delimit the attribute value (onclick="follow('1');") or string (onclick= 'follow("1");')
Use HTML entities to include the quote mark you are using in the data for the attribute value (onclick= 'follow('1');')

JSON String as Javascript function argument

I am trying to define a pure JSON string as an argument in a Javascript function.
Below is the way I want to define it:
Link
Firebug gives me an error alert: unterminated string literal, even when I escape the double-quotes on the JSON string.
How can I solve this?
Thanks.
Use " for your double quotes, then in js_func(), replace them with actual double quote characters (") before evaluating your JSON string. (thanks for the demo Matthew, I updated your fiddle with the example from the question:)
http://jsfiddle.net/brillyfresh/kdwRy/1/
simply defining the link as Link works fine. JSON is valid JavaScript, you don't need to enclose it in ''s.
I also suggest to use an EventListener (element.addEventListener()), this makes the html cleaner and would reduce this problem to nothing.
ryou are either trying to pass the parsed object or pass a string
Object: onclick="js_func(arg_1, arg_2, {'key': 'value'});"
String: on_click="js_func('arg_1', 'arg_2', '{\"key\": \"value\"}'); return false"
All I've got handy to test is firebug interpreter but both worked fine for me.
>>>>'{\"key\": \"value\"}'
"{"key": "value"}"
>>>> {'key': 'value'}
Object {key="value"}
(I don't mean to presume whether arg_1 and arg_2 are strings or variable names, and it doesnt matter. just did the same thing as with the JSON)

Categories

Resources