Reputation: 640
I've been playing around with Svelte 3. I'm trying to create a basic Link component that's used like this:
<Link to="http://google.com">Google</Link>
My component renders a normal HTML <a>
tag with a favicon in front of the link text:
<script>
export let to
const imageURL = getFaviconFor(to)
</script>
<a href={to}>
<img src={imageURL} alt={`${title} Icon`} />
<slot />
</a>
The title
variable I'm showing in the alt attribute for my <img>
tag needs to be the text value of the unnamed slot. This is a really basic example, but is there any way to get the value of a slot like this?
Upvotes: 14
Views: 7564
Reputation: 11706
In the mean time I found another (even better and not so hacky) way:
<script>
export let to
let slotObj;
const imageURL = getFaviconFor(to)
</script>
<a href={to}>
<img src={imageURL} alt={slotObj? slotObj.textContent + ' Icon' : 'Icon'} />
<span bind:this={slotObj}><slot/></span>
</a>
Upvotes: 9
Reputation: 11706
This hack will work.
Add a hidden span or div to bind the slot text:
<span contenteditable="true" bind:textContent={text} class="hide">
<slot/>
</span>
And update your code like this:
<script>
export let to
let text;
const imageURL = getFaviconFor(to)
</script>
<a href={to}>
<img src={imageURL} alt={text + ' Icon'} />
{text}
</a>
Upvotes: 3