11ty & URLs
Best Practices for URL Creation in 11ty
When building a website with the 11ty (Eleventy) static site generator, creating proper URLs is crucial for maintaining a well-structured and easily navigable site. In this post, we'll explore the best methods for creating URLs in 11ty.
The Problem with Relative URLs
You might be tempted to use relative URLs like this:
<a href="./sitemap/">Sitemap</a>
While this can work, it's not ideal. Relative URLs can break if you move pages around or change your site structure. Let's look at some better alternatives.
1. The url
Filter: Your Go-To Solution
The url
filter is the most recommended way to create URLs in 11ty. It automatically resolves paths based on your site structure:
<a href="/sitemap/">Sitemap</a>
This method is flexible and works correctly regardless of where your page is located in the site hierarchy.
2. Absolute Paths: When You Know the Exact Location
If you're certain about the path from the root of your site, you can use absolute paths:
<a href="/sitemap/">Sitemap</a>
This method is straightforward but less flexible if your site structure changes.
3. Permalinks: For Specific Pages
For linking to specific pages, you can set permalinks in the front matter of those pages:
---
permalink: /sitemap/
---
Then reference them in your templates:
<a href="">Sitemap</a>
This method is great for maintaining consistent URLs for important pages.
4. Using eleventyNavigation
for Complex Structures
For more complex site structures, consider using the eleventyNavigation
plugin. It helps manage your site's navigation and can automatically generate URL structures.
Netlify
If you're struggling to find out why your .html web pages are not working, review the Netlify setting in 'post-processing' for 'Pretty URLs'
If you want to keep you .html files (some people do), uncheck this value.
Conclusion
While there are several ways to create URLs in 11ty, the url
filter method stands out as the most versatile and robust approach. It handles both relative and absolute URLs correctly, ensuring your links remain intact even as your site evolves.
Remember, good URL structure is not just about functionality—it's about creating a better experience for your users and improving your site's SEO. Choose the method that best fits your project's needs and stick to it consistently throughout your site.
Happy coding with 11ty!