Eleventy project logo

Meta Description and Keywords in Eleventy

Print Friendly and PDF

Posted: May 1, 2023 | Categories: Eleventy

As I built out this site, I realized that since I had a description for many of the posts and an array of one to many categories for each, I could populate each page's meta description and keywords properties.

Description was easy, I added a description property to my post template and populated it for my newer posts. With that in place, the code simply checks to see if the description property is populated and, if so, adds it to the page:

{% if description %}
<meta name="description" content="{{ description }}" />
{% endif %}

For keywords, building the comma separated list of categories is a little ugly in Liquid (doable, but not elegant):

{% if categories.length > 0 %}
<meta
name="keywords"
content="
{% for cat in categories %}
{{ cat }}
{%- unless forloop.last %},
{% endunless %}
{% endfor %}"
>

{% endif %}

Instead, I decided to add a GetKeywords shortcode in the project's eleventy.config.js like this:

eleventyConfig.addShortcode("GetKeywords", function (categories) {
return categories.join(", ");
});

Now, with access to the keywords array of categories, adding it to each page's header was as easy as:

{% if categories.length > 0 %}
<meta name="keywords" content="{% GetKeywords categories %}">
{% endif %}

The difference is in code readability and output. In the first example, Eleventy generates the following HTML:

<meta
name="keywords"
content="
John M. Wargo,

John Wargo,

johnwargo
"
>

For the second, Eleventy generates the following:

<meta name="keywords" content="John M. Wargo, John Wargo, johnwargo">

Which, as I hope you see, is much cleaner; with the solution I picked I got cleaner code and output - always a goal for me.

Next Post: Gadget Man

Previous Post: Eleventy Extra Spaces in Category List

If this content helps you in some way, please consider buying me a coffee.

Header image: Eleventy Project Home Page.