More Articles

Capitalize All Words With Nunjucks

How to create a custom filter in Eleventy that capitalizes all words in a given string.

Written on May 5, 2024 | About 3 min reading time

New tools in your inbox every Monday!

Creating an Eleventy Custom Filter to Capitalize All Words in a String

Eleventy is a powerful static site generator that allows you to extend its functionality through custom filters and plugins. While Nunjucks, the templating engine used by Eleventy, provides a built-in capitalize filter to capitalize the first letter of a string, it doesn't offer a filter to capitalize all words in a string out of the box.

In this article, we'll explore how to create a custom filter in Eleventy that capitalizes all words in a given string.

The Need for a "Capitalize All Words" Filter

Sometimes you might want to capitalize the first letter of each word in a string. For example, if you have a title or a heading that needs to be capitalized according to specific styling guidelines, the built-in capitalize filter won't suffice.

Here's an example of how the capitalize filter works in Nunjucks:


<!-- Input -->
<h1>{{ "this is a title" | capitalize }}</h1>

<!-- Output -->
<h1>This is a title</h1>

As you can see, only the first letter of the string is capitalized, but the rest of the words remain in their original case.

Creating a Custom "Capitalize All Words" Filter

To create a custom filter that capitalizes all words in a string, we can leverage the power of JavaScript's regular expressions and string manipulation methods.

// Custom filter to capitalize each word in a string
config.addFilter("capitalizeWords", function(value) {
  if (typeof value !== 'string') {
    return ''; // or handle the undefined case as needed
  }

  return value.replace(/\b\w/g, char => char.toUpperCase());
});

Let's break down this code:

  1. config.addFilter("capitalizeWords", function(value) { ... }) is the Eleventy method to add a custom filter. The first argument is the name of the filter (capitalizeWords), and the second argument is a function that defines the filter's behavior.
  2. if (typeof value !== 'string') { return ''; } is a safety check to ensure that the input value is a string. If the input is not a string, the filter will return an empty string. You can modify this behavior based on your requirements.
  3. return value.replace(/\b\w/g, char => char.toUpperCase()); is where the magic happens. This line uses the replace method to replace all occurrences of word boundaries (\b) followed by a word character (\w) with the uppercase version of that character (char.toUpperCase()). The g flag ensures that the replacement is done globally, across the entire string.

Here's an example of how you can use this custom filter in your Eleventy templates:


<!-- Input -->
<h1>{{ "this is a title" | capitalizeWords }}</h1>

<!-- Output -->
<h1>This Is A Title</h1>

With the capitalizeWords filter applied, all words in the string are capitalized.

Customizing the Filter's Behavior

The provided implementation of the capitalizeWords filter is a basic example, and you might want to customize it based on your specific requirements. For instance, you might want to exclude certain words from being capitalized or handle special characters differently.

To customize the filter's behavior, you can modify the regular expression or add additional logic within the filter function.


const excludedWords = ['a', 'an', 'the', 'and', 'or', 'but', 'for', 'nor', 'as', 'at', 'by', 'in', 'of', 'on', 'to'];

config.addFilter("capitalizeWords", function(value) {
  if (typeof value !== 'string') {
    return '';
  }

  return value.replace(/\b\w/g, char => {
    const word = char.toLowerCase();
    if (excludedWords.includes(word)) {
      return char.toLowerCase();
    } else {
      return char.toUpperCase();
    }
  });
});

In this modified version, an array of excludedWords is defined, containing common words that should remain in lowercase. The filter function checks if the current word is in the excludedWords array, and if so, it keeps the word in lowercase; otherwise, it capitalizes the word.

By customizing the filter's behavior, you can tailor it to your specific needs and ensure that it works correctly with your content and styling guidelines.

Conclusion

Creating custom filters in Eleventy allows you to extend the functionality of the static site generator and streamline your template logic. The "Capitalize All Words" filter demonstrated in this article is a simple yet powerful example of how you can enhance Eleventy's capabilities to suit your project's requirements.

Remember, when creating custom filters or plugins, it's essential to consider edge cases, performance implications, and maintainability. Always strive for modular and reusable code, and consider sharing your custom filters or plugins with the Eleventy community to benefit others.

October Featured Tools

Reach.at

Make an easy way to contact you! Create & share a friendly contact page today.

Explore

Strapi

Strapi is the leading open-source headless CMS. It’s 100% JavaScript, fully customizable and developer-first.

Explore

We Recommend...

Top products featured for the article.

Strapi

Strapi is the leading open-source headless CMS. It’s 100% JavaScript, fully customizable and developer-first.

Explore

BirdSeed

12 powerful website tools to uniquely convert your visitors into future customers, all built into one button

Explore

AtomPay

AtomPay is a platform that enables freelancers, side-hustlers, solopreneurs, and content creators to easily accept & process payments from their audience, community and social media.

Explore

Contentfly

Get blog posts, social posts, email copy & more from the top 1% of writers. Scale up quickly and with ease.

Explore

Sponsored

See all Tools

A Little Extra Reading

Feel like reading more? Here are some extra articles to check out!

See all Articles