0

I am returning a DTML Template generated using Python's Zope and assigning it a JS variable by evaluating it in browser. My template would look like:

var html = <dtml-var "html">

# which is nothing but
var html = "<html>
<body>
Hello
</body>
</html>
"

This is not valid since Javascript expects double quotes to close before a newline character as explained in some questions like JavaScript string with new line - but not using \n.

I figured that I could actually do:

var html = String.raw`<dtml-var "html">` 

which works in Chrome, however String.raw doesn't exist in IE 11. Are there any alternatives that I can use?

Alternatively, can I fix this problem in Python by doing the below snippet? Are there any caveats to be aware of?

# Replace newline character to \n literally.
html.replace("\n",\\n")

# Escape the double quotes
html.replace("\n",\\n").replace("\"", "\\\"") i.e replace " with \"
Community
  • 1
  • 1
Nishant
  • 20,354
  • 18
  • 69
  • 101
  • why do you need `String.raw`? (it doesn't look like you do, it looks like you need template strings, which won't work in IE, ever). also, you can use `JSON.stringify()` to make literals from regular strings. – dandavis Apr 15 '16 at 19:37
  • `String.raw` they say is for Templates so I used that and it worked. `JSON.stringify` is in Javascript right? I mean how do I get into JS from my database in the first place? Are you telling me to store differently? I store the HTML directly to database and retrieve it. There could be multiple solutions for this problem, but I am just thinking which approach would be good. – Nishant Apr 15 '16 at 19:42
  • 1
    ohh, simply turn the string from the DB into JSON on the backend, and it arrives on the client as a valid JS string, even with line-breaks in the DB source string... – dandavis Apr 15 '16 at 19:43
  • so you mean `var html = JSON.parse(jsonified);` i guess I need to understand what `JSON` is better :) if you realize I am also executing it. – Nishant Apr 15 '16 at 19:48
  • 1
    yes, that should un-pack the string into a multi-line/quote-having string without issue. – dandavis Apr 15 '16 at 19:49

0 Answers0