Keep newlines when using HTML codecs in Grails views

The Grails XSS prevention functionality is quite convenient, so I turned it on using:

grails.views.default.codec = "html"

Although, this creates a problem with html textareas. If we finish textareaand use Enter to break lines, new lines are saved in the database, but they are ignored in the view. I could use <%=%>, and replaceAll('\n',"<br>")to correct the line breaks, but the HTML code is filled in textarea, will be screened and there will be no support for XSS!

How would you fix this problem?

+5
source share
1 answer

Before rendering your text field in GSP, you can

  • encode your string as HTML
  • <br/>.

lib grails-app/taglib:

class LinesTagLib { 
  def lines = { attrs, body -> 
    out << attrs['string'].encodeAsHTML().replace('\n', '<br/>\n')
  } 
}

encodeAsHTML() , HTML- ( <%=expression%> ${expression}):

    <g:lines string="<%=savedTextarea%>" />

:

class HTMLLinesCodec{ 
  static encode = { str -> 
    str.encodeAsHTML().replace('\n', '<br/>\n')
  } 
}

GSP, , :

<%@ defaultCodec="HTMLLines" %>
+10

All Articles