sveltejs / svelte

web development for the rest of us
https://svelte.dev
MIT License
80.3k stars 4.28k forks source link

svelte:content #7634

Open KieranP opened 2 years ago

KieranP commented 2 years ago

Describe the problem

Each page has a different page header. Need a way to pass data from the main page view to a child of the layout view. Currently complicated using stores. Would clean things up using a method like Ruby on Rails content_for by allowing svelte:fragment to accept a name, and be able to call it later with svelte:content

Describe the proposed solution

In the page view:

<svelte:fragment name="page-header-title">
  Test
</svelte:fragment>

<svelte:fragment name="page-header-action">
  <a href="..."></a>
</svelte:fragment>

In the page banner component:

<div>
  <h1>
    <svelte:content from="page-header-title" />
  </h1>

  <div class="actions">
    <svelte:content from="page-header-action" />
  </div>
</div>

Alternatives considered

Open to suggestions

Importance

would make my life easier

babichjacob commented 2 years ago

Do you think named slots already achieve this?

KieranP commented 2 years ago

@babichjacob Slots can't be passed to sibling components. This is a slimmed down version of what I have in my layout file:

<main>
  <Header />
  <Banner />
  <Page />
</main>

Banner is where the banner contents are displayed/styled, but Page is the one that sets the banner contents. Banner contents varies per page. Currently there is no native way to set content for one component via another. I either have to bubble an event up to the parent and back down, or set content on a store, but storing HTML in a svelte store feels wrong.

JAAvander commented 2 years ago

I would also say that named slots are a good approach. It depends a bit on how your layout component is used.

Here is one example that might work for you Layout.svelte: ```svelte
``` Banner.svelte: ```svelte

``` and lastly Page.svelte: ```svelte Test Remaining page content here... ``` This setup of course assumes that you can decide where, how and when your layout component is instantiated.