问题
I am still not that familiar with the Jade template engine. Is there a way to convert the new lines such as \n to br tags and at the same time keep the other content encoded?
For example
.replace(/\n/g,'</br>')
applied over the encoded value should do the work. However I am not sure how to encode the value and get the result. Is there any helper for this?
回答1:
You can use jades escape method and replace the linebreaks in the return value of that like so:
p !{escape(foo).replace(/\n/g, '<br/>')}
I am not aware of any built-in functionality for your use case.
Looks like pug got rid of the escape function, so this is what you would have to use now:
p !{foo.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/\n/g, '<br/>')}
回答2:
if you don't exactly need <br>
, you can simply put your text within <pre> tag. All whitespaces (including new lines) will be displayed as typed.
Or you could set css rule white-space: pre
to preserve whitespace preformatting. Check MDN on this.
回答3:
escape method, even converts simple space (' ') characters to "%20".
MDN says escape is deprecated and it is meant for encoding strings in url, not html content. Another solution,
each line in foo.split(/\n/)
= line
br
回答4:
You can do that simple:
p !{someString.replace(/\n/g, '<br/>')}
Note that this method will correctly escape string.
回答5:
Most answers say you need to do p !{foo.replace(/\n/g)}
. However, that is not enough: \n
in regex matches the new line character so you will need to escape the \
in \n
. You can do that by adding a additional \
to \n
.
The final result:
p !{foo.replace(/\\n/g, '<br />')}
NOTE: If you want to escape the other characters too, you can just add: .replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')
EDIT:
You can use p #{foo.replace...}
to correctly escape all characters in html tags. This can be useful if you want to prevent users from inserting <script>...</script>
tags in a input field to hack your website.
来源:https://stackoverflow.com/questions/14540788/jade-convert-new-lines-to-br-and-keep-the-content-encoded