Creating a New Element
In Eleventy, reusable components can be created using Nunjucks macros. Here's how you can create your own:
Step 1: Create a New Nunjucks File
Create a New Nunjucks File: Decide on a name for your new element and create a .njk file in the _includes/elements directory. For example, for a custom link component, you might create a file named customLink.njk.
Step 2: Define the Macro
Define the Macro: Inside your .njk file, use the {%macro%} syntax to define your reusable component. You can specify parameters that allow for customization of the component when it's used. Here's an example for a custom link element:
{% macro customLink(text, url, linkClass = "default-class") %}
<a href="{{ url }}" class="{{ linkClass }}">{{ text }}</a>
{% endmacro %}
Step 3: Import and Use the Macro
To use your new component in a page or template, first import the macro at the top of your .njk file where you want to use it:
{% import "elements/customLink.njk" as elements %}
Step 4: Invoke the Macro
After importing, you can use the macro by calling it with any required parameters. For example:
{{ elements.customLink("Eleventy Docs", "https://www.11ty.dev/docs/", "docs-link-class") }}
Step 5: Customize as Needed
The parameters you defined in your macro can be adjusted for each use case, allowing for versatile and reusable components across your project.