Skip to content

How can I emulate Liquid’s where on Nunjucks? #1776

Answered by pdehaan
patrulea asked this question in Q&A
Discussion options

You must be logged in to vote

I haven't tried using Nunjucks' rejectattr filter yet, but this might get you somewhat closer:

// Useful for trying to compare nested properties...
const _get = require("lodash.get");

module.exports = (eleventyConfig) => {
  eleventyConfig.addNunjucksFilter("where", (arr, key, expected) => {
    if (expected === undefined) {
      return arr.filter(item => !!_get(item, key));
    }
    return arr.filter(item => _get(item, key) === expected);
  });
  // ...
}
{% for post in collections.posts | where("data.draft", false) %}
  <p data-draft="{{ post.data.draft }}">{{ post.data.title }}</p>
{% else %}
  <p>No posts found</p>
{% endfor %}

Not sure that it will work exactly like LiquidJS where

Replies: 4 comments 12 replies

Comment options

You must be logged in to vote
7 replies
@pdehaan
Comment options

pdehaan May 14, 2021
Collaborator

@patrulea
Comment options

@pdehaan
Comment options

pdehaan May 14, 2021
Collaborator

@patrulea
Comment options

@pdehaan
Comment options

pdehaan May 14, 2021
Collaborator

Answer selected by patrulea
Comment options

You must be logged in to vote
1 reply
@pdehaan
Comment options

pdehaan May 14, 2021
Collaborator

Comment options

You must be logged in to vote
1 reply
@patrulea
Comment options

Comment options

You must be logged in to vote
3 replies
@patrulea
Comment options

@pdehaan
Comment options

pdehaan May 22, 2021
Collaborator

@patrulea
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants