Using Svelte, how do I populate a <style> tag in <svelte:head> with a Javascript string variable?
Asked Answered
D

1

8

Using Svelte, what I want to accomplish is being able to style my html using the css property of a post object I have.

I thought, no problem, just add a style tag to my svelte:head with {post.css}. It will drop my post.css data right into the style tag, and viola’, problem solved. But, no, problem not solved. When I view the element in my browser, I see

<style>{post.css}</style>

instead of

<style>
  p{
    color: purple;
    font-weight: 900;
  }
 </style>

I have created a work around, where I set the innerText of the <style> tag after onMount, but I don’t like it, and would prefer to do it a cleaner way.

What I want…

<script>
  export let post = {
    html: `<p>This is purple</p>`,
    css : `
      p{
        color: purple;
        font-weight: 900;
      }
    `
    }  
</script>

<svelte:head>
  <style>{post.css}</style>
</svelte:head>

{@html post.html}

What I have to do to make it work…

<script>
  import { onMount } from "svelte";

  export let post = {
    html: `<p>This is purple</p>`,
    css : `
      p{
        color: purple;
        font-weight: 900;
      }
    `
    }

  onMount(() => {
    let styler = document.getElementById("styler");
    styler.innerText = post.css
  });
</script>

<svelte:head>
  <style id="styler"></style>
</svelte:head>

{@html post.html}

If you have any other alternatives to using the css property to style the html property of the post object, or know how to get Svelte to recognize {post.css} in a <style> tag, please let me know.

Directed answered 3/12, 2019 at 15:15 Comment(0)
H
15

You can do this:

{@html `<style>${post.css}</style>`}

Bear in mind that the styles in post.css will apply to the entire page, not just to the post's HTML.

Demo

Hardbitten answered 3/12, 2019 at 21:11 Comment(2)
Doesn't seem to work in SvelteKit. I'm getting Error while preprocessing src/routes/__layout.svelte:1:3: Unknown wordAdduce
@Casimir If there's a postcss preprocessor in your stack, it can give you the "Unknown word" error. In that case, split up the style tag into 2 strings like {@html `<`+`style>${post.css}</style>`}Bartholomeus

© 2022 - 2024 — McMap. All rights reserved.