How to show String new lines on gsp grails file?

后端 未结 3 1754
独厮守ぢ
独厮守ぢ 2021-01-28 02:51

I\'ve stored a string in the database. When I save and retrieve the string and the result I\'m getting is as following:

This is my new object

相关标签:
3条回答
  • 2021-01-28 03:33
    ${raw(adviceInstance.advice?.encodeAsHTML().replace("\n", "<br>"))}
    

    This is how i solve the problem.

    0 讨论(0)
  • 2021-01-28 03:49

    Firstly make sure the string contains \n to denote line break. For example :

    String test = "This is first line. \n This is second line";
    

    Then in gsp page use:

    ${raw(test?.replace("\n", "<br>"))}
    

    The output will be as:

    This is first line.
    This is second line.
    
    0 讨论(0)
  • 2021-01-28 03:52

    Common problems have a variety of solutions

    1> could be you that you replace \n with <br>

    so either in your controller/service or if you like in gsp:

    ${adviceInstance.advice?.replace('\n','<br>')}
    

    2> display the content in a read-only textarea

     <g:textArea name="something" readonly="true">
      ${adviceInstance.advice}
     </g:textArea>
    

    3> Use the <pre> tag

    <pre>
     ${adviceInstance.advice}
    </pre>
    

    4> Use css white-space http://www.w3schools.com/cssref/pr_text_white-space.asp:

    <div class="space">
    </div>
    
    //css code:
    
    .space {
     white-space:pre
    }
    

    Also make a note if you have a strict configuration for the storage of such fields that when you submit it via a form, there are additional elements I didn't delve into what it actually was, it may have actually be the return carriages or \r, anyhow explained in comments below. About the good rule to set a setter that trims the element each time it is received. i.e.:

    Class Advice {
     String advice
      static constraints = {
         advice(nullable:false, minSize:1, maxSize:255)
      }
    
      /*
       * In this scenario with a a maxSize value, ensure you 
       * set your own setter to trim any hidden \r
       * that may be posted back as part of the form request
       * by end user. Trust me I got to know the hard way.
       */
      void setAdvice(String adv) {
        advice=adv.trim()
      } 
    
    }
    
    0 讨论(0)
提交回复
热议问题