Supercharging Your 11ty Projects with Macros

In the world of static site generators, Eleventy (11ty) stands out for its flexibility and simplicity. One of the most powerful features it offers is the ability to use macros. If you're not familiar with macros, think of them as reusable code snippets that can significantly streamline your development process. Let's dive into how you can leverage macros to supercharge your 11ty projects.

What Are Macros?

Macros in 11ty are essentially functions that you can define in your template files. They allow you to encapsulate repeating patterns of HTML and logic, making your code more DRY (Don't Repeat Yourself) and easier to maintain.

The Power of Macros

  1. Reusability: Write once, use everywhere. Macros allow you to define a component once and reuse it throughout your site.
  2. Maintainability: Need to update a component? With macros, you only need to change it in one place.
  3. Readability: Macros can make your template files much cleaner and easier to read.
  4. Flexibility: Macros can accept parameters, allowing you to create flexible, customizable components.

Creating Your First Macro

Let's create a simple macro for a social media link:


{% macro socialLink(platform, url, classes="") %}
  <a href="{{ url }}" class="social-link {{ classes }}">
    <svg class="icon icon-{{ platform }}">
      <use xlink:href="#icon-{{ platform }}"></use>
    </svg>
    <span class="sr-only">{{ platform | title }} page</span>
  </a>
{% endmacro %}

This macro creates a social media link with an SVG icon and screen reader text.

Using Your Macro

Once defined, you can use your macro like this:


{% from "macros/social-links.njk" import socialLink %}

<footer>
  {{ socialLink("twitter", "https://twitter.com/yourprofile") }}
  {{ socialLink("facebook", "https://facebook.com/yourpage") }}
</footer>

Best Practices for Macros

  1. Organize Your Macros: Keep your macros in a dedicated folder, like _includes/macros/.
  2. Keep Them Focused: Each macro should do one thing and do it well.
  3. Document Your Macros: Add comments explaining what each macro does and what parameters it accepts.
  4. Use Default Values: Provide default values for parameters when it makes sense.

Advanced Macro Techniques

As you become more comfortable with macros, you can explore more advanced techniques:

  1. Nested Macros: You can call macros within other macros.
  2. Macro Libraries: Create libraries of related macros for different components.
  3. Conditional Logic: Use if statements within macros to create more dynamic components.

Conclusion

Macros are a powerful tool in your 11ty toolbox. They can help you write cleaner, more maintainable code and speed up your development process. Start small with simple macros, and as you get more comfortable, you'll find more and more ways to leverage them in your projects.

Happy coding!