Home > OS >  Can't insert a <polygon> inside an <svg> by printing its html with {@html} in Svelt
Can't insert a <polygon> inside an <svg> by printing its html with {@html} in Svelt

Time:08-17

This is my parent component:

<script>
    import ObjOne from './ObjOne.svelte'
</script>

<svg width="182px" height="146px" viewBox="0 0 182 146">
    <ObjOne></ObjOne>
</svg>

And this is ObjOne:

<script>
  let html = '<polygon id="Path" fill="#999999" points="109.9999 146.25 109.9999 98.75 182.4999 98.75 182.4999 146.25" />'
</script>

{@html html}

The polygon doesn't render, unless I put the <polygon> directly in the component's body, as you can see in the REPL. Is there any workaround? I need to dynamically insert elements in an <svg>. I tried with version and xmlns properties on the <svg> but it didn't help.

REPL: https://svelte.dev/repl/14b354d830184a8d994cae6d223e4c85?version=3.49.0

CodePudding user response:

This is a known issue with how @html generates elements in SVG. In this case the compiler does not have enough context to know that the element is supposed to be an SVG element, so it will end up with the wrong namespace (HTML).

As a workaround you could add a dummy group:

<g>{@html html}</g>
  • Related