Hide lines in Jade scripts

I have a Jade template with lines like this:

html head title Person Details script var Person = function () { this.name = "#{person.name}", this.contactInfo = "#{person.contactInfo}" } ... 

When I create this template, I pass the person object to it.

The problem is that some of the fields that I pass to the template (e.g. person.contactInfo above) may have newlines, 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." } ... 

... that causes the Unexpected Token error.

Can newline characters be avoided to avoid this problem? Or should I avoid them before sending data to the rendering engine?

0
source share
1 answer

From what I heard, rendering data into scripts is bad practice. I would think that this is a problem with what you are experiencing. A potentially better option would be to use #{JSON.stringify(person)} and then JSON.parse() this with JSON.parse() on the client side. This way, you don’t have to worry about which characters are in your person object, as the JSON object takes care of this 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 really strange, who knows. Ideally, I think you should do XMLHttpRequest when the page loads and uses JSON as the content-type , so you don't do anything funky.

+1
source

Source: https://habr.com/ru/post/1493644/


All Articles