Where is the proper place to escape quotes in Play Framework?
Asked Answered
S

1

3

I have the following flow:

  1. A user is presented with a form.
  2. He fills in the form fields, and submits to the controller, which persists this to the DB
  3. On another page, the Controller gets this record from the DB, and passes it to the view
  4. The view captures it as a javascript variable: var foo = '${user.bar}';

Now, if the user enters this string in the form:

I have a quote - ' - very dangerous

then the quote is passed through all the way to the DB and back, and results in a corrupt javascript statement:

var foo = 'I have a quote - ' - very dangerous';

What is the best place to escape this character, and how? I don't want to do it manually for each template usage, it's tedious and error prone.

Seng answered 7/6, 2012 at 8:53 Comment(2)
I just found the java extensions module. Is this really the best we can do - use this ${user.bar.addSlashes().raw()}? It is rather verbose and error prone. playframework.org/documentation/1.2.4/javaextensionsSeng
If you are using Rythm template engine, it could be var foo = '@user.bar.escapeJavaScript()'; . Check playframework.org/modules/rythm for more about Rythm template engineSusquehanna
T
4

The data is the data. If it contains a quote, it contains a quote, and it has to be stored that way in the database. You need to escape the quote when using this String a a JavaScript string literal.

You could use Apache commons-lang StringEscapeUtils.escapeECMAScript() method to do that, or you could encode your Java objects into JSON strings, and parse the JSON string in your JavaScript code.

Tired answered 7/6, 2012 at 8:59 Comment(6)
Isn't this approach both verbose and error prone? Is this the best we have right now?Seng
BTW, see also my comment above about the java extensions module.Seng
What exactly are you hoping for? A magic tool that will know that you're generating a JS literal string and that will magically escape things for you? When you generate HTML, you must html-escape your strings. When you're generating JS strings, you must JS-escape your strings.Tired
When I'm generating HTML, Play handles the escaping for me, no? Perhaps what I'm hoping for is another play operator to cut down on the verbosity ... $$user.foo$$. I guess this probably does't exist right now, not even in a 3rd party module. I'll accept your answer for now.Seng
I don't know enough about Play to know if some magic notation or tag exists. My point was that it's at the view layer that escaping must be done. And I doubt Play escapes anything for you.Tired
It does HTML escaping by default: #5765179Seng

© 2022 - 2024 — McMap. All rights reserved.