Reputation: 653
I'm using Svelte, and I want to create a component that will allow me to do something like this:
<CodeDisplay>
<button class="btn">Button</button>
</CodeDisplay>
CodeDisplay.html should look something like this:
<slot></slot>
<code><slot></slot></code>
Essentially, what I want is a component that will first render the HTML code that I place within the component, and then I want to display the code itself. (I'm building a documentation system.)
Seems to be like you can't use <slot></slot>
more than once which makes sense.
How would I accomplish what I'm trying here. I really want to avoid duplicating the HTML code twice in my code for every example in the documentation. I just thought it would be nice to have a component that in general, I can pass some HTML, and then the component will render the HTML and show the code.
EDIT: I just realized I could do something like this:
{{{html}}}
<pre><code>{{html}}</code></pre>
<script>
export default {
data() {
return {
html: '',
}
}
};
</script>
And display it like this:
<CodeDisplay html='<button class="btn">Button</button>'/>
But I'm getting some errors with this (that happen inconsistently).
Upvotes: 3
Views: 1901
Reputation: 7147
Have you seen named <slot>
s?
<slot name="slot-one"></slot> // Show rendered HTML
<slot name="slot-two"></slot> // Show HTML as string
When you create your HTML-snippet example with backticks, you can render it in slot-one
and display it as a (nicely formatted multi-line) example in slot-two
:
let mySnippet = `<div>
<div>
<span>Hello</span>
</div>
</div`;
I'm not a SvelteJS expert, but you you can test/check here with this example.
Upvotes: 2