简体   繁体   中英

How to show String new lines on gsp grails file?

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

Testing multiple lines

-- Test 1

-- Test 2

-- Test 3

That is what I get from a println command when I call the save and index methods.

But when I show it on screen. It's being shown like:

This is my object Testing multiple lines -- Test 1 -- Test 2 -- Test 3

Already tried to show it like the following:

${adviceInstance.advice?.encodeAsHTML()}

But still the same thing.

Do I need to replace \\n to
or something like that? Is there any easier way to show it properly?

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. ie:

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()
  } 

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

这就是我解决问题的方法。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM