aureliaaurelia-templating

Insert template element into slot element


I've built a custom element with a few named slots, something like this:

<template>
    <header>
        <slot name="header"></slot>
    </header>
    <slot name="body"></slot>
    <footer>
        <slot name="footer"></slot>
    </footer>
</template>

And I use it like this:

<my-custom-element>
    <div slot="header">
        <h1>Title</h1>
        <p>Description</p>
    </div>
    <div slot="body">
        <h2>Body content</h2>
        <p>Body content</p>
        <p>Body content</p>
    </div>
    <div slot="footer">
        <p>Copyright 2018</p>
        <ul>
            <li>Facebook</li>
            <li>Twitter</li>
            <li>Instagram</li>
        </ul>
    </div>
</my-custom-element>

However, as you can see this results in my DOM looking like header > div > content, footer > div > content etc.

I figured I could use a template element instead of a div in order to get rid of the unnecessary (and sometimes style breaking) div, unfortunately this does not seem to work:

<my-custom-element>
    <template slot="header">
        <h1>Title</h1>
        <p>Description</p>
    </template>
    <template slot="body">
        <h2>Body content</h2>
        <p>Body content</p>
        <p>Body content</p>
    </template>
    <template slot="footer">
        <p>Copyright 2018</p>
        <ul>
            <li>Facebook</li>
            <li>Twitter</li>
            <li>Instagram</li>
        </ul>
    </template>
</my-custom-element>

Is there a way to send multiple elements into a slot without wrapping them first?


Solution

  • Ok so turns out you can simply use the slot attribute on multiple elements instead;

    <my-custom-element>
        <h1 slot="header">Title</h1>
        <p slot="header">Description</p>
        <h2 slot="body">Body content</h2>
        <p slot="body">Body content</p>
        <p slot="body">Body content</p>
        <p slot="footer">Copyright 2018</p>
        <ul slot="footer">
            <li>Facebook</li>
            <li>Twitter</li>
            <li>Instagram</li>
        </ul>
    </my-custom-element>
    

    This is pretty unreadable and cumbersome though. And it just doesn't feel like good code. Being able to use a template[slot] would be much better imo.