Loop through object properties nunjucks - nunjucks

I've got following model:
items: {
someId1:
{
property1....
},
someId2: {...},
someIdN: {...}
}
I would like to get a for-loop in my template (nunjucks) which goes through all the "someId's".
Does anyone have any idea how? A normal for-loop does not work since it's not an array and since I use the "someId.." for a reference in another template I cannot put it to an array.
Any help would be awesome.

This answer is actually right on the Nunjucks homepage:
<ul>
{% for name, item in items %}
<li>{{ name }}: {{ item }}</li>
{% endfor %}
</ul>
In your case this would be:
<ul>
{% for someId, item in items %}
<li>{{ someId }}: {{ item.property1 }}</li>
{% endfor %}
</ul>
As you can use the for loop for arrays and object/hashes.

You can use nested loops like this:
<ul>
{% for item in items %}
{% for something in item.someId1 %}
<li>
{{ something.property1 }}
</li>
{% endfor %}
{% endfor %}
</ul>
For this json object:
items: {
someId1: {
property1: "It makes you want to shout! Raise your hands up and..."
},
someId2: {...},
someIdN: {...}
}

I think the answer you're looking for is to use something like this:
{% for tuple in items | dictsort %}
<p>{{tuple[0]}}, {{tuple[1]}}</p>
{% endfor %}
Very simply the dictsort filter returns a list of tuples(key-value pair) from the object in a sorted manner, which can then be accessed as follows.
So, if the object is
items: {
someId1:
{
property1....
},
someId2: {...},
someIdN: {...}
}
You would get,
[['someid1',{property1: ..}], ['someid2','...'], ['someid3','...']]
Now you can just use the loop as if you were looping through an array. Keep in mind that additional nested properties must be handled manually too.
The previous answers suggested manually extracting each property. What if I wanted the same page with data that has 5 properties as well as 10 properties. What if I wanted all keys by not specifying them? Which is something I came across and stumbled upon this question. As of 2022, we can use dictsort but previous answers may worked just as well.

Related

How can I specify an 11ty collection in frontmatter?

On my website, I want to show a list of collection items on pages corresponding to each collection. For example on the Games page, I want to show a list of all game related articles, on the Politics page, I want to show a list of all politics related articles, etc.
What I have right now is one Nunjucks template file for each such page, which I don't particularly like since they are the same except for the collection to show. Here is two of my templates, for my politics articles and for my games articles, where I extend a common boilerplate (base.njk) and in the main block, I first print some Markdown content and then comes the list of collection items:
{# politics.njk #}
{% extends "base.njk" %}
{% block main %}
<main>
{{ content | safe }}
<ul class="postlist no-bullets">
{% for item in collections.politics %}
{% include "partials/collection-list-item.njk" %}
{% endfor %}
</ul>
</main>
{% endblock %}
{# games.njk #}
{% extends "base.njk" %}
{% block main %}
<main>
{{ content | safe }}
<ul class="postlist no-bullets">
{% for item in collections.games %}
{% include "partials/collection-list-item.njk" %}
{% endfor %}
</ul>
</main>
{% endblock %}
As you can see, the only difference between these two files is collections.politics and collections.games. I would want to use one template, and in the frontmatter specify which collection I want. Since I'm already having one Markdown file per page the template used (for writing stuff before I begin listing articles), it would have been nice if it was possible. For example:
<!-- politics.md -->
---
layout: articles-list.njk
title: Politics
listCollection: collections.politics
---
# Politics
Below is a list of all politics articles I've written.
<!-- games.md -->
---
layout: articles-list.njk
title: Games
listCollection: collections.games
---
# Games
I think about games a lot. Below is a list of articles I've written on the topic.
{# articles-list.njk #}
{% extends "base.njk" %}
{% block main %}
<main>
{{ content | safe }}
<ul class="postlist no-bullets">
{% for item in listCollection %}
{% include "partials/collection-list-item.njk" %}
{% endfor %}
</ul>
</main>
{% endblock %}
Is it possible to do what I want to do in some other way than to have multiple template files?
You might be able to get to the collection using computed data, though I'm not sure if you have access to the collections there.
A simpler approach: Set your frontmatter field to the name of the colletion you want to display as a string, then use that to get the collection in the template:
<!-- politics.md -->
---
layout: articles-list.njk
title: Politics
listCollection: 'politics'
---
{# articles-list.njk #}
{% extends "base.njk" %}
{% block main %}
<main>
{{ content | safe }}
<ul class="postlist no-bullets">
{% for item in collections[listCollection] %}
{% include "partials/collection-list-item.njk" %}
{% endfor %}
</ul>
</main>
{% endblock %}
The way I handled this on my blog (https://github.com/cfjedimaster/raymondcamden2020) was like so:
I create a collection of my categories. I do this by using .eleventy.js and eleventyConfig.addCollection. I use some JavaScript to get all of my posts, iterate over each ones list of categories, and creating a unique list. At the end, I've got a collection called categories.
eleventyConfig.addCollection("categories", collection => {
let cats = new Set();
let posts = collection.getFilteredByGlob("_posts/**/*.md");
for(let i=0;i<posts.length;i++) {
for(let x=0;x<posts[i].data.categories.length;x++) {
cats.add(posts[i].data.categories[x].toLowerCase());
}
}
return Array.from(cats).sort();
});
I then made one page, categories.liquid, that is reponsible for generating my category pages. It's rather simple:
---
pagination:
data: collections.categories
size: 1
alias: cat
permalink: "categories/{{ cat | myEscape }}/"
layout: category
renderData:
title: "{{ cat }}"
---
Notice I use cat for each item in the category and notice I've got nothing else in here. All the layout is done in the category layout page.
Here's the top portion of my category page:
---
layout: default
---
{% assign posts = collections.posts | getByCategory: cat %}
So given I've got a collection of posts where each post has N categories assigned to it, I wrote a custom filter that just reduces this down to a post that has cat as one of it's categories.
S the end result is N category pages filled posts assigned to that category.

Shopify Help Returning Line Item Properties

I am having an issue retrieving the line tem properties of an order. The problem is that the code I am using is not displaying anything.
I am able to get the order line items, but the properties of the line item (like if I have a form field name properties[SomeText] or properties[Color])
Here is a simplified version of what I am using:
{% for item in order.line_items %}
Sku: {{item.item.sku}}
Product Title: {{item.title}}
{% for prop in item.properties %}
Properties: {{ prop.first }} = {{ prop.last }}
{% endfor %}
{% endfor %}
In the example above, the values for Sku and Product Title are working, but I am not getting any values returned for the Properties. I know they exist because they show when I go an view an order.
So, I'm not sure what I've done incorrectly. Any help will be greatly appreciated.
After looking at the Order's raw XML, I noticed that instead of using prop.first and prop.last, I changed it to prop.name and prop.value and it works.
{% for item in order.line_items %}
Sku: {{item.item.sku}}
Product Title: {{item.title}}
{% for prop in item.properties %}
Properties: {{ prop.name }} = {{ prop.value }}
{% endfor %}
{% endfor %}

October CMS-How pass variable to a component in a {% for ... endfor %} loop?

I can't understand this. In this example trucs is an non empty array. When I wrote :
{% for truc in trucs %}
{{ truc.foo }}
{% component 'myComponent' truc=truc %}
{% enfor %}
I can read {{ truc.foo }} but array truc is empty in my component myComponent whereas trucs is available. Could it be linked with the Page execution life cycle handlers ? In that case, when and/or where could I inject truc ?

How to filter Taxonomies using Rust-based Zola / Tera?

I have recently discovered Zola and Tera (Rust frameworks for statically-generated websites) and found them amazing.
I'm trying to filter specific category pages to display in a section on the same page. To illustrate, I wrote some code like this:
<div class="content">
{% block content %}
<div class="list-posts">
{% for page in section.pages %}
{% for key, taxonomy in page.taxonomies %}
{% if key == "categories" %}
{% set categories = taxonomy %}
{% for category in categories %}
{% if category == "rust" %}
<article>
<h3 class="post__title">{{ page.title }}</h3>
</article>
{% endif %}
{% endfor %}
{% endif %}
{% endfor %}
{% endfor %}
</div>
{% endblock content %}
</div>
There should be MULTIPLE sections of the code above for different categories, e.g. "rust", "java", etc.
I wrote the code to explain my question, but it isn't the way I want it (and it doesn't work when the sections are duplicated).
How do I do the filtering of the particular category when the sections/pages are loaded?
The front-matter metadata in the content file is:
title = "A web page title"
[taxonomies]
categories = ["rust"]
If you see my example code above, I have to access it first via a hash map, then an array, in order to filter all pages which is "rust".
The filter below doesn't work:
for page in section.pages | filter(attribute="taxonomies.categories", value="rust"
I managed to resolve it. First, I did tests like this:
HTML test print output
{% set categories = get_taxonomy(kind="categories") %}
{% set rustItems = categories.items | filter(attribute="name", value="rust") %}
{% set javaItems = categories.items | filter(attribute="name", value="java") %}
{{ rustItems[0].pages | length }}
<br>
{{ rustItems[0].pages[0].title }}
<br>
{{ rustItems[0].pages[1].title }}
<br>
I was able to pick up the title as set in the .md file.
So I moved on further and I did:
{% set categories = get_taxonomy(kind="categories") %}
{% set category = categories.items | filter(attribute="name", value="business") | first %}
{% for page in category.pages %}
{{ page.title }}
... etc.
The above code will filter the pages for category taxonomy.

Filter site.related_posts in Jekyll

I am very new to Jekyll and Ruby (yet, very excited).
Without using a plugin, I am trying to find a way to filter the site.related_posts.
For example, I am reading the post with title Foo and categories A, B.
The site contains in total 3 posts:
Foo (Categories: A, B)
Bar (Categories: A, C, D)
Zoo (Categories: B, F)
By the default, in Jekyll we do this:
{% for post in site.related_posts limit:5 %}
{% endfor %}
However, the above code returns all the (3) posts.
A post contains many categories, so categories should be an array.
How can I modify the code and return only those whose categories intersect with the current post's categories?
(In this example, I would like the code to return only Foo and Zoo.)
I don't have the ability to test this right now, but something like this will work given Liquid's limited syntax:
{% for post in site.related_posts limit:5 %}
{% assign match = false %}
{% for category in post.categories %}
{% if page.categories contains category %}
{% assign match = true %}
{% endif %}
{% endfor %}
{% if match %}
<li>{{ post.title }}</li>
{% endif %}
{% endfor %}
Make sure each post has a category in the YAML front matter, then add this to where you would like to show the post relating CATEGORY_NAME:
{% for post in site.categories.CATEGORY_NAME %}
<li>
<a href="{{ post.url }}">
<img src="{{ post.thumbnail }}">
<p>{{ post.excerpt }}</p>
</a>
</li>
{% endfor %}

Resources