【问题标题】:Sort titles with localCompare使用 localeCompare 对标题进行排序
【发布时间】:2020-09-20 08:28:45
【问题描述】:

使用 Eleventy 作为静态站点生成器我无法弄清楚如何对某些字母表中的标题进行排序(在我的例子中,拉脱维亚语,lv)。 Documentation related sorting

到目前为止,以下脚本适用于英语。

  eleventyConfig.addCollection("postsDescending", (collection) =>
    collection.getFilteredByGlob("src/posts/*.md").sort((a, b) => {
      if (a.data.title > b.data.title) return 1;
      else if (a.data.title < b.data.title) return -1;
      else return 0;
    })
  );

在我看来,我尝试了 localeCompare,但收到错误 collection.getFilteredByGlob(...).from is not a function

const alphabet = ['a','ā','b','c','č','d','e','ē','f','g','ģ','h','i','ī','j','k','ķ','l','ļ','m','n','ņ','o','p','r','s','š','t','u','ū','v','z','ž'];
    eleventyConfig.addCollection("postsDescending", function(collection) {
        return collection.getFilteredByGlob("src/posts/*.md").from(alphabet).sort(function(a, b) {
           return a.localeCompare(b, 'lv', { sensitivity: 'base' });
        });
    });

不用说我是 Javascript 的初学者......非常感谢任何帮助!

【问题讨论】:

  • 是什么让您认为有.from() 方法可用? getFilteredByGlob 返回一个标准的 JavaScript Array
  • 感谢您调查问题。搞定了!

标签: javascript node.js eleventy


【解决方案1】:

原来我可以自己解决这个问题。

  eleventyConfig.addCollection("postsDescending", (collection) =>
    collection.getFilteredByGlob("src/posts/*.md").sort((a, b) => {
return a.data.title.localeCompare(b.data.title, 'lv', { sensitivity: 'base' });
    })
  );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-28
    • 1970-01-01
    • 2021-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多