Home > Net >  Display String as HTML
Display String as HTML

Time:06-22

How can I render a string to be displayed as an html? I am trying to accept an array of strings. I should be able to check if the string is an html, if yes, I need to display it with html formatting, otherwise display normally as a string.

Example:

<template>
  <div v-for="msg in msgs" :key="msg">
    {{ msg }}
  </div>
</template>
// msgs will look like this:
const msgs = ['hello there', '<b>print this in bold</b>', '<br/>', 'and this is in another line']

I tried to do something like this:

<template>
  <div v-for="msg in msgs" :key="msg">
     {{ isHtml(msg) ? processAsHtml(msg) : msg }}
  </div>
</template>

Where processAsHtml is like this:

const parser = new DOMParser()

function processAsHtml (htmlString) {
  return parser.parseFromString(htmlString, 'text/html')
}

But this prints the html lines as "[object HTMLDocument]"

Help!

Thanks!

CodePudding user response:

you can use v-html

<template>
  <div v-for="msg in msgs" :key="msg">
     <div v-html="msg">
     </div>
  </div>
</template>

CodePudding user response:

You can use v-html for row html, but be aware of XSS vulnerabilities:

new Vue({
  el: "#demo",
  data() {
    return {
      msgs: ['hello there', '<b>print this in bold</b>', '<br/>', 'and this is in another line']
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <div v-for="msg in msgs" :key="msg" v-html="msg"></div>
</div>

  • Related