11ty / eleventy-plugin-webc

Adds support for WebC *.webc files to Eleventy
https://www.11ty.dev/docs/languages/webc/
120 stars 10 forks source link

Can i use slots in layouts? #63

Open niklasgrewe opened 1 year ago

niklasgrewe commented 1 year ago

Can i use slots in layouts like in this way?

<!-- layouts/base.webc -->
<head>
   <meta charset="UTF-8" />
   <meta name="viewport" content="width=device-width, initial-scale=1.0" />
   <slot name="meta"></slot>
</head>
<!-- layouts/home.webc -->
---
layout: layouts/base.webc
---

<link slot="meta" rel="stylesheet" href="assets/css/home.css">
MatthewNichols commented 1 year ago

Oh I would like that, I used the similar feature in Nunjucks. I will try it later to see if it works.

niklasgrewe commented 1 year ago

@zachleat any recommendations or workarounds about this?

zachleat commented 1 year ago

The clearest workaround for now is to bypass Eleventy layouts altogether and use a WebC component instead.

<my-base-layout>
  <link slot="meta" rel="stylesheet" href="assets/css/home.css">
</my-base-layout>

Another less documented method is to use the html helper from eleventy-plugin-bundle:

<script webc:type="js">
webc.helpers.html(`<link rel="stylesheet" href="assets/css/home.css">`, "meta")
</script>

where the second argument meta is an arbitrary bucket name—and then template usage might be:

<!-- layouts/base.webc -->
<head>
   <meta charset="UTF-8" />
   <meta name="viewport" content="width=device-width, initial-scale=1.0" />
   <meta webc:nokeep @raw="getBundle('html', 'meta')"/>
</head>
d3v1an7 commented 1 year ago

I've landed on the following. Have included some extra flavour re: how I'm handling titles, as it might be helpful if you're working on <head> :)

<!-- _components/site-head.webc -->
<script webc:setup>
  const metadata = {
    title: 'Default title',
    description: 'Default description',
  };
  function setTitle(title) {
    return title ? `${title} — ${metadata.title}` : metadata.title;
  }
</script>
<meta charset="utf-8" />
<title @text="setTitle($data.title)"></title>
<meta name="description" :content="$data.description || metadata.description" />
[etc...]
<!-- _layouts/base.webc -->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta webc:nokeep webc:is="site-head" />
  </head>
  <body>
  [etc...]
<!-- index.webc -->
---
layout: base.webc
title: This will be prefixed to metadata.title
---

Hello world.

Let me know if that helps :)