Igor
Igor

Reputation: 1464

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?

Upvotes: 0

Views: 2073

Answers (3)

Salu Khadka
Salu Khadka

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

Upvotes: 1

srsajid
srsajid

Reputation: 1787

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

This is how i solve the problem.

Upvotes: 1

V H
V H

Reputation: 8587

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

}

Upvotes: 6

Related Questions