2

In Vaadin 8 there is the possibility to show preformatted text with help of the Label component -

Label preLabel = new Label(
    "Preformatted text is shown in an HTML <pre> tag.\n" +
    "Formatting such as\n" +
    "  * newlines\n" +
    "  * whitespace\n" +
    "and such are preserved. HTML tags, \n"+
    "such as <b>bold</b>, are quoted.",
    ContentMode.PREFORMATTED);

https://vaadin.com/docs/v8/framework/components/components-label

How to achieve the same with Vaadin 23 ? I need to pretty print text on the page which contains line breaks \n

alexanoid
  • 24,051
  • 54
  • 210
  • 410

1 Answers1

3

The Html class in Flow is intended for freeform HTML content: https://vaadin.com/api/platform/23.1.4/com/vaadin/flow/component/Html.html

Note that the content given to it must be enclosed in a top-level html element, e.g. "<span>Preformatted<b>stuff</b></span>" is ok, while "Preformatted <b>stuff</b>" is not.

If you only need line breaks, however, you could also try the Pre class which renders as a element https://vaadin.com/api/platform/23.1.4/com/vaadin/flow/component/html/Pre.html

E.g. Pre pre = new Pre("This text has line\nbreaks");

Rolf
  • 2,178
  • 4
  • 18
  • 29
  • Thanks! I tried the following `Html html = new Html("" + text + "");` Where `text` contains line breaks, but it didn't work. What am I doing wrong? Also, how to update the text in `Html` component one more time? – alexanoid Aug 04 '22 at 10:49
  • If you use the Html class, you'll need to encode line breaks as
    – Rolf Aug 04 '22 at 10:50
  • And unfortunately Html instances are immutable, like Strings. Pre, on the other hand you can update with setText – Rolf Aug 04 '22 at 10:52
  • Doesn't the `Pre` component have the drawback that it also uses a monospace font by default? As yet another alternative, you can thus consider a `Span` component with the `white-space` style set to e.g. `pre-line` :) – Leif Åstrand Aug 04 '22 at 10:53
  • @LeifÅstrand thanks! `Span` with the mentioned style is the best option! I also tried `Pre` and `TextArea` in read-only mode. Thanks All! – alexanoid Aug 04 '22 at 11:21
  • TIL there's a whitespace setting :D Nice! – Rolf Aug 04 '22 at 13:35