Search code examples
sveltehtml-escape-characters

Is it possible to render svelte component's (end result) HTML code as a string (escape/show raw HTML code)?


I have a simple PrimaryButton.svelte component that contains "HTML" only (no script or style tags) and looks like this:

<button class="btn-primary btn accent--br">Primary button</button>

Then I imported the component into App.svelte and it renders in the browser just fine, but I also want to show the HTML code of the component as well.

App.svelte looks like this:

<script>
    import PrimaryButton from "./components/Buttons/PrimaryButton.svelte";
</script>

<PrimaryButton/>

I tried to render it as a string like this: {PrimaryButton} instead of <PrimaryButton/>. But the browser displayed this string:

class PrimaryButton extends SvelteComponentDev { constructor(options) { super(options); init(this, options, instance$5, create_fragment$5, safe_not_equal, {}); dispatch_dev("SvelteRegisterComponent", { component: this, tagName: "PrimaryButton", options, id: create_fragment$5.name }); } }

I was kind of hoping it would show the HTML of the component as a string instead but I do sort of understand why that's not happening.

How can I show the output HTML of the component as a string in the browser? What would you do?


Solution

  • I ended up defining .html files instead and then importing them into svelte components using this plugin: https://www.npmjs.com/package/rollup-plugin-string

    In the svelte component I can either render the HTML or show the string of the HTML code:

    <script>
        import button from "./button.html";
    </script>
    
    {button}
    
    {@html button}