Recipes
External Links
Learn how to leverage custom components to automatically handle external links.
When writing markdown, you often want to link to external resources. You can do this with the standard markdown syntax:
But by default, this will render a link that looks like this:
Meaning when a user clicks the link, they'll be taken away from your site, which is often not the desired behavior. Let's take a look at how we can automatically handle links for external and internal resources.
Create a Custom Component
To override the default a
element that is rendered for links, we'll need to define a component that will be used in its place.
To keep things simple, we'll create a component called a.svelte
in our src/lib/blueprints/default
directory:
The href
attribute will be passed to the component as a prop, so we can use it to determine if the link is internal or external, based on the first character of that prop. If the first character is a /
, we'll assume it's an internal link, otherwise we'll assume it's an external link.
You can also get fancy and add a custom icon used to indicate that the link is external:
Now that we have our custom component, we'll need to export it from a blueprint component for it to override the default a
element.
Create a Blueprint
Note
If this is your first time hearing about blueprints, you should read more about Blueprints before proceeding.
We'll create a simple blueprint for this example, whose only job is to export our custom a
component:
Apply the Blueprint
We'll use this blueprint as our default
blueprint, which will be used for all markdown files that don't specify a blueprint.
And that's it! Now when you link to an external resource, it will be rendered using your custom component, which will automatically handle external links for you.