drake035
drake035

Reputation: 2897

How to render line breaks contained in a string?

Line breaks contained in my strings merely render as <br> instead of actual line breaks.

I tried to use back-ticks to no avail. Is there a simple way to have line breaks rendered on the page, ideally without modify my code too deeply?

Markup:

<div
  v-for="item in faqItems"
  :key="item.id"
>
  <span class="faq-item-title">
    {{ item.title }}
  </span>
  <span class="faq-item-details">
    {{ item.text }}
  </span>
  <svg-icon name="chevron-down"></svg-icon>
</div>

JS:

faqItems: [
  {
    title: 'Nullam vehicula arcu ipsum',
    text: 'Donec sit amet nisl finibus, pharetra orci ut, aliquet diam.<br><br>Nunc cursus libero luctus nunc vestibulum placerat. Mauris vel dolor sit amet orci rutrum sollicitudin.<br><br>Donec neque leo, porttitor a diam et, sodales volutpat libero.'
  },
  {
    title: 'In iaculis egestas nisl',
    text: 'Etiam a elementum diam. Praesent lobortis pulvinar lacus, sit amet vehicula tortor.'
  }

Upvotes: 1

Views: 192

Answers (2)

tao
tao

Reputation: 90277

One way is to replace your <br>s with text line breaks (\n) and keep using it as text in layout:

{
  title: 'Nullam vehicula arcu ipsum',
  text: 'Donec sit amet nisl finibus, pharetra orci ut, aliquet diam.\n\nNunc cursus libero luctus nunc vestibulum placerat. Mauris vel dolor sit amet orci rutrum sollicitudin.\n\nDonec neque leo, porttitor a diam et, sodales volutpat libero.'
}

As Daniel pointed out, literal line breaks don't work in <span>. Unless you map it to .innerText property of the <span> => Example - which, under the hood, transforms all literal breaks into <br>s and divides the text into different text nodes, accordingly).


The other way is to use the dedicated Vue directive for this purpose, which parses the string as html: v-html.

<span class="faq-item-details" v-html="item.text" />

Upvotes: 1

kots
kots

Reputation: 465

Use backticks and then add css entries as follows:

<div
  v-for="item in faqItems"
  :key="item.id"
>
  <span class="faq-item-title" style="white-space: pre-wrap;">
    {{ item.title }}
  </span>
  <span class="faq-item-details" style="white-space: pre-wrap;">
    {{ item.text }}
  </span>
  <svg-icon name="chevron-down"></svg-icon>
</div>

Upvotes: 0

Related Questions