I'm trying to display code as text, unrendered. However, when I use the <pre>
or <code>
tag with html tags within it, LWC is rendering what is inside those tags in the browser instead of ignoring and displaying as text, which is what would normally happen. Is there any way around this?
1 Answer
Everything in the template is evaluated. If you want to safely escape those elements, assign the string to an attribute and use that. Here's a quick demo.
import { LightningElement } from 'lwc';
export default class App extends LightningElement {
code = 'This is a <br/> tag. It does not break to the next line.';
}
<template>
<pre>
{code}
</pre>
</template>
This is also useful for loading data from a file or record and displaying the contents in this manner.
LWC is rendering what is inside those tags in the browser instead of ignoring and displaying as text, which is what would normally happen.
<div>something</div>
rather than having the browser evaluate the tags as a div. Like how in the lwc design components show the code snippets of use.