Pulling all the information from the database, formatted

Sirs, my application has a lot of information.
But when viewing by the browser …
It does not appear formatted in html.

What would it take to display fully formatted, as it was inserted in the database …
It all appears in a single line.

Below my show.html.eex

> <ul>
>   <li>
>     <strong>Description:</strong>
>    <%= @vaga.descricao_vaga %>
>   </li>
> </ul>

Maybe add a helper function that would replace all newline characters like \n with <br> with the help of Phoenix.HTML.Format.text_to_html/2.

defmodule YourAppWeb.SomeHelperView do
  use YourAppWeb, :view

  @doc """
  Shows text in paragraphs by converting new line characters `\n` to `<br>` tags.
  """
  def paragraphed_text(text)

  @spec paragraphed_text(nil) :: []
  def paragraphed_text(nil), do: [] # in case your database returns `nil`

  @spec paragraphed_text(String.t()) :: Phoenix.HTML.safe()
  def paragraphed_text(text) do
    text_to_html(text)
  end
end

then your template would become

<ul>
  <li>
    <strong>Description:</strong>
    <%= YourAppWeb.SomeHelperView.paragraphed_text(@vaga.descricao_vaga) %>
  </li>
</ul>

(you can alias YourAppWeb.SomeHelperView in your view, then the function call would be a bit shorter)

Or if you are sure @vaga.descricao_vaga would never be nil, just use text_to_html/2 directly

<ul>
  <li>
    <strong>Description:</strong>
    <%= text_to_html(@vaga.descricao_vaga) %>
  </li>
</ul>

or if you are not particularly sure, but still don’t want to create new functions just to handle nil

<ul>
  <li>
    <strong>Description:</strong>
    <%= text_to_html(@vaga.descricao_vaga || "") %>
  </li>
</ul>
3 Likes

Everything worked.
Thank you