user395788
user395788

Reputation: 245

Svelte Substitution in <script> within svelte:head

I'm using svelte to create a personal website. I want to place a chunk of javascript code in the head of my final HTML code, which is based on a svelte component. So I have something like

<svetle:head>
    <script> var url = "myurl.com/"; </script>
<svetle:head>

within a [slug].svelte file. I want to substitute a value that passed into this component as a prop within the script. I tried doing something like

<svetle:head>
    <script> var url = "myurl.com/{post.slug}"; </script>
<svetle:head>

Unfortunately this doesn't work. If the substitution {post.slug} were to occur outside of <script>, svelte would perform the substitution just fine, before passing the resulting html to the client. However because it's within the <script>, svelte seems to be assuming that I must want literally "myurl.com/{post.slug}", instead of "myurl.com/my-post-name" . I think this may be because {} has meaning in javascript.

Note that I've tried every combination of "myurl.com/{post.slug}", "myurl.com/"{post.slug}, myurl.com/${post.slug}. Any placement of {post.slug} within <script> does not substitute.

How can I get svelte to perform this substitution at the same time it performs every other substitution in the .svelte component? I can't imagine there isn't a way to do this, but the svelte documentation doesn't seem to address this.

Upvotes: 5

Views: 2466

Answers (2)

cevaris
cevaris

Reputation: 5794

Seemingly you can inject your script via @html svelte function.

<script lang="ts">
    const postSlug: string = "...";
</script>

<svelte:head>

    {@html `<script>
        var url = "${postSlug}";
    </script>`}

</svelte:head>

One downside is that this whole <script/> block will need to render as a string then. Which would make it hard to manage larger JS logic. But it works for my case when injecting env variables into simple <script/> blocks.

Upvotes: 6

Joshua Collinsworth
Joshua Collinsworth

Reputation: 31

This is kinda janky, but if the value you need is a text string, you could put it inside a <meta> tag, then select it.

<svelte:head>
  <meta name="myVar" content={post.slug} />
  <script>
    var url = document.querySelector('meta[name=myVar]')
    console.log(url.getAttribute('content'))
  </script>
</svelte:head>

However, I suspect there's probably a much better way to do this without such a workaround, and knowing a bit more about how the code will consume the variable would be helpful in providing a better answer.

Upvotes: 3

Related Questions