1

I want that some tags from component to go to head tag. I want to put in the slot named head. How could achieve this ?

layout.astro

<html>
    <head>
        <slot name="head" />
    </head>
    <body>
        <slot />
        <mycomponent />
    </body>
</html>

mycomponent.astro

<link .... slot="head">
<div>
    ...
</div> 
anaconda
  • 1,065
  • 10
  • 20

1 Answers1

1

Solution

It is possible to place a tag, but only from where you call a Layout where the single <head> is placed, using slots like this

in the Layout.astro you create a

  • default slot and
  • a named slot e.g. name="head" but you could use any name

    <head>
        <title>{title}</title>
        <slot name="head"/>
    </head>
    
    <body>
        <slot />
    </body>

then in your page or in the Component that is calling the Layout


<Layout title="Welcome to Astro.">
    <link slot="head" rel="icon" type="image/svg+xml" href="/favicon.svg" />
    <main>
        <h1>Astro</h1>
    </main>
</Layout>

Clarifications

  • The slot concept is independent from the Layout and head
  • The Layout component can have any name and can be used from any component
  • In Astro there can be only one single <head> element per page, all other used <head> tags will stay where they are and will not be moved by the compiler to the main top <head>
  • A page and all of its children components can use the slot concept to fill it tags inside the single parent <head> tag via slots
  • This only works if the component directly includes the component e.g. Layout that is providing the slots

References

Note : The reference below from the Astro Documentation website recommends to "place the single <head> and its contents in a layout component."

https://docs.astro.build/en/guides/troubleshooting/#using-head-in-a-component

named slots :https://docs.astro.build/en/core-concepts/astro-components/#named-slots

wassfila
  • 1,173
  • 8
  • 18
  • Thank you! This will work I just wonder if it's possible out of the box from compent to parent – anaconda Jan 29 '23 at 13:57
  • no, directly from component to parent without slots is not possible, I provided a reference from astro doc that state it. – wassfila Jan 29 '23 at 14:52