3

I'm trying to render some HTML string in template, but I want them to be string, I don't want to render "rich text"

I started with:

<template>
  <div>{{'something <like /> this'}}</div>
</template>

but vue will render the code above into follwing: <like /> will be rendered as html tag

<div>{{'something <like></like> this'}}</div>

but what I want is this:

<div>something &lt;like/&gt; this</div>

I know I can put the text inside data

<template>
<div>{{text}}</div>
</template>
<script>
export default {
  data() {
    return {
      text: 'something <like /> this'
    }
  }
}
</script>

but this would become tedious, and how can I do it directly inside template

2 Answers 2

2

I think you need to pre-process your string first like this

text.replace(/&/g, "&amp;").replace(/>/g, "&gt;").replace(/</g, "&lt;").replace(/"/g, "&quot;");

Then you can use it in the template

Sign up to request clarification or add additional context in comments.

Comments

2

You'll need to replace the characters < and > as you've pointed out, but you'll also need to use the v-html directive since the tags in the string literal break the mustache binding.

In your script:

methods: {
  htmlToText(html) {
    return html.replace(/</g, '&lt;').replace(/>/g, '&gt;')
  },
}

In your template:

<div v-html="htmlToText('something <like/> this')"></div>

Doing <div>{{ htmlToText('something <like/> this') }}</div> will not work.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.