11ty / eleventy

A simpler site generator. Transforms a directory of templates (of varying types) into HTML.
https://www.11ty.dev/
MIT License
16.76k stars 484 forks source link

hyphenated words in collection names #2276

Open inetbiz opened 2 years ago

inetbiz commented 2 years ago

Is your feature request related to a problem? Please describe. allow collection names to have a hyphen. technical-seo vs technical

Describe the solution you'd like allow hyphens

 eleventyConfig.addCollection("technical-seo", function(collectionApi) {
    return collectionApi.getFilteredByGlob("technical-seo/*.md").sort(function(a, b) {
      //return a.date - b.date; // sort by date - ascending
      return b.date - a.date; // sort by date - descending
    });
});
pdehaan commented 2 years ago

Technically you can, but it's an invalid JavaScript variable name, so you have to access it via array/object syntax (ie: collections["technical-seo"]):

---
title: Technical SEO
---

<ul>
{% for post in collections["technical-seo"] %}
  <li><a href="{{ post.url }}">{{ post.data.title }}</a> ({{ post.date }})</li>
{% endfor %}
</ul>

OUTPUT

<ul>
  <li><a href="/technical-seo/three/">Three</a> (Tue Mar 22 2022 17:00:00 GMT-0700 (Pacific Daylight Saving Time))</li>
  <li><a href="/technical-seo/two/">Two</a> (Sun Feb 20 2022 16:00:00 GMT-0800 (Pacific Standard Time))</li>
  <li><a href="/technical-seo/one/">One</a> (Wed Jan 19 2022 16:00:00 GMT-0800 (Pacific Standard Time))</li>
</ul>

Interestingly, if you want to paginate over a hyphenated collection name, it seems to "just work" (which I learnt about 3 seconds ago):

---
pagination:
  data: collections.technical-seo
  size: 2
  alias: posts
---

<ul>
{% for post in posts %}
  <li><a href="{{ post.url }}">{{ post.data.title }}</a></li>
{% endfor %}
</ul>

OUTPUT

<ul>
  <li><a href="/technical-seo/three/">Three</a></li>
  <li><a href="/technical-seo/two/">Two</a></li>
</ul>

and…

<ul>
  <li><a href="/technical-seo/one/">One</a></li>
</ul>

To further confuse things, I think using collections.technical-seo works for my .liquid template, but returned an empty array for .njk template (probably because it couldn't figure out if "technical-seo" is a collection name or unexpected mathematical operation).

Unsatisfying personal recommendation: Don't. Name it "technicalSeo" or something easier/consistent. I'm not 100% certain if this is something Eleventy could solve/fix, or if it's down to the parser/lexer of each rendering engine (which is maybe why I saw different results between a simple LiquidJS and Nunjucks template).

pdehaan commented 2 years ago

Also, please drop a link to your blog. ❤️ I do selfishly enjoy reading some SEO content.