A. Stam
A. Stam

Reputation: 2222

Replace newline with br() in Shiny output

I'm writing a Shiny app in which I display text that is loaded from a database. In the database, there might be texts like so:

This is the first line
and this is the second.

There is a list of these texts that I'm loading from the database, and I want to display them all in their own box. My backend processing of these strings looks more or less like this:

format_text <- function(text) {
    shinydashboard::box(text)
}

output$text_ui <- renderUI({
    map(text_list, format_text) %>%
      tagList()
})

When displaying, this does not respect the newlines that are in the original strings. The entire text is displayed on one line:

This is the first lineand this is the second.

I've tried fixing this by adding the following step in my custom function:

text <- str_replace_all(text, "(\r|\n)", "<br/>")

Which results in the following text:

This is the first line<br/>and this is the second

Which is obviously not what I want either.

Now, I know that I can create new lines using the shiny::br() function. However, I'm struggling to see how I could get those to work at the right points in the string.

A minimal Shiny app to fiddle with can be found here.

Upvotes: 3

Views: 1207

Answers (1)

A. Stam
A. Stam

Reputation: 2222

Ah, the solution turns out to be deceptively simple:

format_text <- function(text) {
    shinydashboard::box(
       HTML(text)
    )
}

Upvotes: 3

Related Questions