Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

and/or on a where_exp expression on Jekyll

I'm trying to use where_exp to filter Jekyll pages based on two categories using or operator:

{% assign sortedPages = site.pages | sort:"date" | reverse | where_exp:"page","page.categories contains 'design-pattern'" %}

But I'm getting this error:

Expected end_of_string but found pipe

Ar or/and operators really supported? I can't figure out how to filter pages using where_exp as shown in my code snippet.

like image 866
Matías Fidemraizer Avatar asked Mar 10 '17 16:03

Matías Fidemraizer


2 Answers

I've managed to solve my issue with some workarounds... It's not a very elegant solution, but as Jekyll isn't about creating actual software architecture... For now, it works flawlessly:

{% assign patterns = "" | split,"" %}

{% for page in site.pages %}
{% if page.categories contains "design-pattern" or page.categories contains "anti-pattern" %}
{% assign patterns = patterns | push:page %}
{% endif %}
{% endfor %}

{% assign sortedPages = patterns | sort:"date" | reverse %}
  1. I create an empty array.
  2. I loop over all pages and I filter them by two possible categories.
  3. I push pages that fulfill the whole condition.
  4. Once I get the filtered page array, I sort and reverse it.
like image 167
Matías Fidemraizer Avatar answered Oct 12 '22 22:10

Matías Fidemraizer


I was unable to replicate the error message you included with your original question. However, as far as filtering based on multiple conditions goes, it is supported. You can also put all of your filters together. The result is much cleaner code 😊

Example

If one wants to set a variable named "sortedPages" equal to "site.pages", but with the following filters:

  • Sort by date
  • Sort in reverse order
  • Only include a page if it has design-pattern and/or anti-pattern as a category

they can do so with the following one-liner:

{% assign sortedPages = site.pages | sort:"date" | reverse | where_exp: "item", "item.categories contains 'design-pattern' or item.categories contains 'anti-pattern'" %}

Answer as multiple lines

Splitting up statements across multiple lines is also supported. Doing so can sometimes improve readability:

{% 
    assign sortedPages = site.pages 
    | sort:"date" 
    | reverse 
    | where_exp: "item", "item.categories contains 'design-pattern' or item.categories contains 'anti-pattern'" 
%}
like image 25
JoshuaTheMiller Avatar answered Oct 12 '22 21:10

JoshuaTheMiller