Meta Description and Keywords in Eleventy

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) {
let returnString = "";
for (let category in categories) {
returnString += categories[category] + ", ";
}
// Remove the last comma
return returnString.slice(0, -2);
});
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.
If this post helps you in some way, please consider buying me a coffee.