Let’s say I have a paragraph with some text that I get from some database:
<p>
{{ text }}
</p>
However, this text may contain some references to other pages in my aplication:
Sample text [reference] sample text
So I would like these references to get turned into links to said pages:
<p>
Sample text <a href="/path/to/reference"> reference </a> sample text
</p>
I tried using the replace function in the script like this:
text.replace(/[(.+)]/,"<a href='/path/to/$1'>$1</a>");
But the characters all get escaped resulting in the anchor html code getting shown on the page.
Is there a way to stop the characters from being escaped, or even another way to turn [references] in the middle of the text into working links to another page?
Advertisement
Answer
If you don’t want your HTML to be escaped, use the v-html
directive.
From the docs:
The double mustaches interprets the data as plain text, not HTML. In order to output real HTML, you will need to use the
v-html
directive:
Example:
var app = new Vue({
el: "#app",
data: function() {
return {
text: "See defect <a href='#'>#12345</a> for details"
};
}
});
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.13/dist/vue.min.js"></script>
<div id="app">
<p>{{text}}</p>
<p v-html="text"></p>
</div>