I have a Jade template with lines like these:
html
head
title Person Details
script
var Person = function () {
this.name = "#{person.name}",
this.contactInfo = "#{person.contactInfo}"
}
...
When I render this template I pass it a person object.
The problem is that some of the fields I pass to the template (such as person.contactInfo above) may have newline characters, and the rendering process outputs something like this:
<html>
<head>
<title>Person Details</title>
<script>
var Person = function () {
this.name = "Joe Schmoe",
this.contactInfo = "Phone: 555-1234.
Address: 555 Main St."
}
...
...which throws an Unexpected Token error.
Can I escape newline characters to avoid this problem? Or must I escape them before sending the data to the render engine?
From what I've heard, rendering data into scripts is bad practice. I would imagine this is the issue looking at what you're experiencing. A potentially better option would be to use #{JSON.stringify(person)} and then parse that using JSON.parse() on the client side. This way you needn't worry what characters are in your person object as the JSON object is taking care of that for you.
html
head
title Person Details
body
input(type="hidden", name="person", value="#{JSON.stringify(person)}")
script
var Person = function () {
var _person = document.querySelectorAll('input[name="person"]').value;
_person = JSON.parse(_person);
for (var key in _person) {
this[key] = _person[key];
};
};
...
Semantically I would put it in an input tag, which is odd really, who knows. Ideally I think you should do an XMLHttpRequest when the page loads and use JSON as the content-type, that way you aren't doing anything funky.