1

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?

Dmitry Boychev
  • 111
  • 1
  • 6

2 Answers2

5

You can use the outerHTML attribute of DOM element.

// PrimaryButton.svelte
<script>
let element;
export let code = "";
onMount(() => {
  code = element.outerHTML
})
</script>

<button bind:this={element} class="btn-primary btn accent--br" href="#">Primary button</button>


// App.svelte
<script>
import PrimaryButton from "PrimaryButton.svelte"

let PrimaryButtonCode;
</script>

<pre>{PrimaryButtonCode}</pre>
<PrimaryButton bind:code={PrimaryButtonCode} />
hackape
  • 14,331
  • 1
  • 22
  • 48
  • I don't want to console log it, I want to show it on the web page along side the rendered button. Am I not understanding something from your answer? – Dmitry Boychev May 01 '21 at 03:18
  • Ok, I sort of figured it out... But not exactly what I want yet. Thanks for your answer – Dmitry Boychev May 01 '21 at 03:22
  • I must point out, there’s no way to get that HTML string without instantiating the component in the first place. Guess you must’ve realized, the component is pure JS, the HTML "template" is encoded in JS, it doesn’t exist anywhere before executing the JS code. – hackape May 01 '21 at 03:49
  • I ended up doing something completely different because it works better for my use case (see my answer). However I do appreciate your answer and I think it is a legitimate way of doing it as well. Just started learning svelte so don't know much yet. – Dmitry Boychev May 01 '21 at 03:55
1

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}
Dmitry Boychev
  • 111
  • 1
  • 6