GitHub Pages can't run custom Jekyll plug-ins so when generating anchors for your headings (i.e. h1
- h6
), you're stuck with JavaScript solutions that will inject anchors. But what if your users don't have JavaScript enabled on their browsers? If you're building a static website, why not make your anchors static as well?
As a part of my "Pure Liquid" series of Jekyll snippets, here is a Liquid snippet that will modify your generated HTML to inject anchors. Want to see it in action? Here are some awesome websites that I know of using this solution ❤️.
- Travis CI Docs (fixed in #1960)
- Bitrise's Documentation
- di's personal website
- sitespeed.io
- Duality's developer docs
- Australia's Vote Flux campaign
- mlpack.org
- Riot.js website
- "Just the Docs" Jekyll theme
- Microsoft's TypeScript website
Want a Table of Contents in your Jekyll layouts without JavaScript or a plug-in?
Check out the sister project over at allejo/jekyll-toc.
Alright, so how do you use it?
-
Download the latest
anchor_headings.html
-
Toss that file in your
_includes
folder -
Where you typically would put
{{ content }}
in your layout, you would instead use this Liquid tag to output your page's content:{% include anchor_headings.html html=content %}
This snippet is highly customizable. Here are the available parameters to change the behavior of the snippet.
Parameter | Type | Default | Description |
---|---|---|---|
html |
string | * | the HTML of compiled markdown generated by kramdown in Jekyll |
beforeHeading |
bool | false | Set to true if the anchor should be placed before the heading's content |
anchorAttrs |
string | '' | Any custom HTML attributes that will be added to the <a> tag; you may NOT use href , class or title |
anchorBody |
string | '' | The content that will be placed inside the anchor; the %heading% placeholder is available |
anchorClass |
string | '' | The class(es) that will be used for each anchor. Separate multiple classes with a space |
anchorTitle |
string | '' | The title attribute that will be used for anchors; the %heading% placeholder is available |
h_min |
int | 1 | The minimum header level to build an anchor for; any header lower than this value will be ignored |
h_max |
int | 6 | The maximum header level to build an anchor for; any header greater than this value will be ignored |
bodyPrefix |
string | '' | Anything that should be inserted inside of the heading tag before its anchor and content |
bodySuffix |
string | '' | Anything that should be inserted inside of the heading tag after its anchor and content |
* This is a required parameter
The performance impact of this snippet on your site is pretty negligible. The stats below were gotten from Jekyll's --profile
option.
Filename | Count | Bytes | Time
-------------------------------------------------+-------+----------+------
# performance on docs.travis-ci.com from ~Aug 2018
_includes/anchor_headings.html | 193 | 1667.96K | 0.695
This snippet may be redistributed under the MIT license.