Heading levels refer to the HTML heading elements of h1
- h6
. Heading levels are important because they describe the structure of the content, and using them in the correct order has several benefits. In addition to helping sighted users find what they’re looking for more quickly, assistive technology users can also easily navigate between or skip headings.
There are several places throughout the site where I list posts. I have a single partial to handle all the different post types that includes the post title, summary, the section if applicable (Articles or Notes), publish date and tags. It’s used on the homepage, the Changelog, and listing pages for Articles, Notes, and tags (e.g., the tag for Eleventy content).
On all of these pages except the homepage the heading should be a h2
. On the homepage the listing is within a section that has a h2
, so those headings should be h3
.
Fortunately this is relatively easy to do! I’m using Nunjucks if expressions and set variable, but I think you could use the same approach with Liquid by using assign.
Here’s a diagram showing the relationship of the partial and layouts…
As the diagram above shows, the partial for the article summary contains a conditional header that sets the value, in this case the heading tag, to a variable titled headingLevel
. If headingLevel
is not present, then h2
is used. This makes the default heading a h2
but allows for variation where needed.
<!-- article-summary.html -->
<{{ headingLevel if headingLevel else 'h2' }} class="promo-article-title">
<a href="{{ item.url }}">{{ item.data.title }}</a>
</{{ headingLevel if headingLevel else 'h2' }}>
On the Articles, Changelog, Notes and tag listing pages the conditional heading code turns into this…
<h2 class="promo-article-title">
<a href="{{ item.url }}">{{ item.data.title }}</a>
</h2>
In the homepage layout headingLevel
is set to h3
…
<!-- home.html -->
{% extends "layouts/base.html" %}
{% set headingLevel = 'h3' %}
{% block content %}{% endblock%}
Which turns the conditional heading code in the partial to this…
<h3 class="promo-article-title">
<a href="{{ item.url }}">{{ item.data.title }}</a>
</h3>
That’s it! A straightforward way to efficiently use partials and ensure you’re creating proper document outlines.