项目作者: pdehaan

项目描述 :
Polyfill the liquidjs map filter into Nunjucks
高级语言: HTML
项目地址: git://github.com/pdehaan/11ty-nunjucks-filter-map.git
创建时间: 2020-03-07T02:19:46Z
项目社区:https://github.com/pdehaan/11ty-nunjucks-filter-map

开源协议:Mozilla Public License 2.0

下载


11ty-nunjucks-filter-map

Polyfill liquid map filter into Nunjucks.

Liquidjs includes a built-in map filter which creates an array of values by extracting the values of a named property from another object.
By default this only works with directly nested properties, and not properties nested more than one level deep, as seen in the following example:

  1. fileSlug:
  2. {{ collections.posts | map: "fileSlug" }}
  3. <!-- Output: [ 'liquid-v1', 'nunjucks-v1', 'liquid-v2', 'nunjucks-v2' ] -->
  4. data.title:
  5. {{ collections.posts | map: "data.title" }}
  6. <!-- Output: [ undefined, undefined, undefined, undefined ] -->

We can polyfill this into Nunjucks using the following custom filter in our .eleventy.js config file, as seen in the following snippet:

  1. // Polyfill the liquidjs "map" filter into Nunjucks templates.
  2. eleventyConfig.addNunjucksFilter("map", (arr, prop) => arr.map(item => item[prop]));
  1. fileSlug:
  2. {{ collections.posts | map("fileSlug") }}
  3. <!-- Output: [ 'liquid-v1', 'nunjucks-v1', 'liquid-v2', 'nunjucks-v2' ] -->
  4. data.title:
  5. {{ collections.posts | map("data.title") }}
  6. <!-- Output: [ undefined, undefined, undefined, undefined ] -->

Success! Sort of.

If you want to be able to use nested properties, you can use something like lodash.get (https://lodash.com/docs/4.17.15#get), and a custom filter in your .eleventy.js config file:

  1. const _get = require("lodash.get");
  2. module.exports = function (eleventyConfig) {
  3. // Build a better `map` filter.
  4. eleventyConfig.addFilter("map2", (arr, prop) => arr.map(item => _get(item, prop)));
  5. // ...
  6. };

Now, you can use this new custom, global map2 filter in your liquid templates:

  1. fileSlug:
  2. {{ collections.posts | map2: "fileSlug" }}
  3. <!-- Output: [ 'liquid-v1', 'nunjucks-v1', 'liquid-v2', 'nunjucks-v2' ] -->
  4. data.title:
  5. {{ collections.posts | map2: "data.title" }}
  6. <!-- Output:
  7. [
  8. 'Liquidjs v1 (native)',
  9. 'Nunjucks v1 (polyfill)',
  10. 'Liquidjs v2 (nested props)',
  11. 'Nunjucks v2 (nested props)'
  12. ]
  13. -->

As well as your Nunjucks templates:

  1. fileSlug:
  2. {{ collections.posts | map2("fileSlug") }}
  3. <!-- Output: [ 'liquid-v1', 'nunjucks-v1', 'liquid-v2', 'nunjucks-v2' ] -->
  4. data.title:
  5. {{ collections.posts | map2("data.title") }}
  6. <!-- Output:
  7. [
  8. 'Liquidjs v1 (native)',
  9. 'Nunjucks v1 (polyfill)',
  10. 'Liquidjs v2 (nested props)',
  11. 'Nunjucks v2 (nested props)'
  12. ]
  13. -->