Open markdown links in a new tab
Recently, I ran into an issue where my website serves links but when you click on it, It will open the link in the same tab. Ugggh! I don’t want to close my website just to open a link. Ideally, it should open the link in a new tab.
How can we do it? It would be easy Eh?
The generic way
Since markdown is eventually rendered as HTML, The most naive way I found was to write HTML in markdown
<a href="http://example.com/" target="_blank">example</a>
No way, I am going to rewrite all my links into HTML. It adds cost later on as well. I will have to add HTML tags to write the link instead of this syntax:
The specialized way
This could vary depending upon the markdown parser you are using. If you’re using Jekyll, like this website, then you can use the following syntax to open links in a new tab.
But, I am not using Jekyll for linkbin. It uses a fairly newer version of Hugo. Hugo ,
v0.62.0 or later, uses Goldmark parser and supports Markdown render hooks. Markdown Render Hooks offer you several ways to extend the default markdown behavior, e.g. resizing uploaded images, opening links in new tabs, or creating mermaid diagrams from code. You can do this by creating templates in the
layouts/_default/_markup directory with base names
render-codeblock. Your directory layout may look like this:
layouts └── _default └── _markup ├── render-image.html ├── render-image.rss.xml ├── render-link.html ├── render-codeblock.html └── render-codeblock-bash.html
Render hook to open link in a new tab
Add the following HTML template file (or render hook) at
<a href="" title="" target="_blank" rel="noopener"></a>
You’ll find that the links now open in a new tab!
For internal blog links (which you would want to open in the same tab), you can use the relative link of the post, e.g. for an
other-post.md file within the
posts directory, you could use
If I’ve missed something or made a horrible mistake if you have any questions regarding this article then feel free to ping me on Twitter. I’m @aaqaishtyaq.