Using Nunjucks to iterate through an array and selectively choose specific items within a for loop

When faced with a large array of items like [5, 21, 83, 74, 12], and my list structure is as follows:

{
  "list:" [
    { "title": "Blue" },
    { "title": "Green" },
    { "title": "Yellow" } ...
  ]
}

I am considering using a for loop to select specific items, but I'm uncertain about the correct syntax and filters. What adjustments should I make to achieve this?

{% for chosen_item in list %}
    {% chosen_item %}
{% endfor %}

Answer №1

If you find yourself in need of applying a filter multiple times, consider adding a custom filter.

var templateEngine  = require('nunjucks');
var env = templateEngine.configure();
env.addFilter('mycustomfilter', array => array.filter(element => element.title == 'Green'));

var renderedHtml = env.renderString(`
    {% for item in list | mycustomfilter %} 
        {{item.id}} {{ item.title}} 
    {% endfor %}
    `, 
    { 
        list: [
            { id: 1, title: 'Blue' },
            { id: 2, title: 'Green' },
            { id: 3, title: 'Yellow' },
            { id: 4, title: 'Green' }
        ]
    }
);

console.log(renderedHtml);

An alternative approach is to utilize if condition whenever needed:

{% for item in list %}
    {{ item if item.title == 'Green' }}
{% endfor %}

or

{% for item in list %}
    {% if item.title == 'Green' %}
        {{ item }}
    {% endif %} 
{% endfor %}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

An AngularJS directive designed to execute after a text input has been modified

I have integrated a bootstrap calendar datepicker that interacts with and updates an <input type="text"> field. As of now, when I use ng-change="myAngularExpression()", the function gets executed the moment the text box is selected. Is there a way t ...

The watch function was triggered for a different key in the array from the one that

What is the best way to limit the watch function to only trigger for the selected key in the data array? import { useSessionStorage } from "@vueuse/core"; const defaultState = { data: [ { key: 1, name: "A" }, { key: 2, nam ...

What is the best way to connect my data with my Backbone Views?

I have successfully set up my views to show test data, and now I want to implement asynchronous data loading to fetch real information. However, I'm a bit confused on the best method to achieve this. Should I manually create AJAX calls? Or maybe utili ...

I am facing difficulty creating a dropdown menu with nested options that only appear when the user hovers over the main selection

Here are the parent options I have and the code I have attempted to build. I would like to include sub-options such as phones, radios, speakers under the electronics parent option and many more. <select id="category" name="category" class="dropDown"& ...

Whenever I attempt to generate a forecast utilizing a tensorflow.js model, I encounter the following error message: "Uncaught TypeError: Cannot read property 'length' of undefined."

I'm currently working on a project to build a website that utilizes a deep learning model for real-time sentiment analysis. However, I've encountered an issue when using the model.predict() function. It throws an error message: Uncaught TypeErro ...

How can we improve our handling of cyclic requires and EventEmitter in our code?

My user service code looks like this: 'use strict'; let events = require('services/events'); module.exports = { create: function (data) { doCreate(data).then(user => { events.emit('user.create'); ...

Retrieving the value of the selected item when it is changed

I am currently using v-select/v-autocomplete in my project: <v-autocomplete v-modal="newRole" :items="roles" label="--Change role--" required return-object item-value="id" item-text=&qu ...

Looking to learn how to replicate data effortlessly with either javascript or jquery?

I am currently trying to figure out how close I am to successfully cloning this div. Honestly, I am a bit lost at this point and could really use some assistance. Should I consider using jQuery for this task? <div id="question20">20. Details of Chi ...

Retrieve form data from Vuex state to make edits

I recently completed a tutorial on Vue to enhance my skills, and I'm now facing an issue while trying to make some changes. The tutorial I followed can be found here. Specifically, I have a "settings" page where users can edit their profile details. ...

Is it possible to utilize the NavigationTimingAPI with asynchronous requests?

Currently, I am working on implementing performance measuring functionality in our project that utilizes custom elements v1. The NavigationTimingAPI provides detailed measurements for various navigation types (navigate, reload, browser back/forward): htt ...

What is causing the animate callback to not properly wait for the completion of the animations?

Both animations are triggered simultaneously (sometimes even multiple times).... <div id="home-bt" class="button"></div> <div id="about-bt" class="button"></div> <div id="beauty-bt" class="button"></div> <div id="pam ...

Having trouble viewing the image slider on an HTML webpage

I've been attempting to incorporate an image slider into my personal website on GitHub, but I've encountered some difficulties as the images are not displaying. Interestingly, I can load individual images without using the slider and they show up ...

The function inputLocalFont.addEventListener does not exist and cannot be executed

Help needed! I created a code to add images using PHP and JS, but I'm encountering an error in my JS that says: inputLocalFont.addEventListener is not a function Here's the code snippet: <div> <img src="<?php echo $img_path.& ...

Viewing HTML web pages using Mozilla Firebox

Printing an HTML table with lots of content has been a challenge for me. Google Chrome didn't work, so I switched to Mozilla Firefox. However, now Firefox is breaking the page inside the table. My question is how can I trigger print preview in Firefox ...

Is it possible to incorporate two ng-repeat directives within a single td element in a table?

The results so far Expected outcome Please advise me on how to incorporate two ng-repeats within one td. When I use a span tag afterwards, the expected result is not achieved. I have used one ng-repeat in the td and the other in a span tag, which is why t ...

Swap out a particular component during the testing phase

Currently, I am running tests on my React-Redux application using Jest. Within my API calls, I have integrated a fetch module called cross-fetch. However, I am looking to substitute this with fetch-mock. Take a look at my directory structure: Action.js i ...

Determine the number of documents in MongoDB that meet a specific pattern using

In my database, I have records that contain various URLs, such as https://www.youtube.com/watch?v=blablabla. My goal is to tally the number of URLs for each individual site. For example: [{ site: 'youtube.com', count: 25 }, { sit ...

Rotating Camera around a Vector3 Point in Three.js

Let me get straight to the point - math is not my strong suit. What may be a piece of cake for you is like solving complex equations in outer space for me. Currently, I am using Three.js with CSS3DRenderer to construct a virtual art gallery. What I reall ...

Top tip for implementing toggle functionality with a specified duration in React.js

I am incorporating React into my web application. I understand how to implement the toggle logic - maintaining a boolean value in my state and updating it when I interact with the toggle trigger. However, I am struggling with how to add animation to this ...

Uh-oh! The module "side-channel" cannot be found. An error occurred in the loader with code 936 when trying to run the command "npm start"

During the execution of npm start to view my React app, I encountered the following error: > react-scripts start node:internal/modules/cjs/loader:936 throw err; ^ Error: Cannot find module 'side-channel' Require stack: - C:\Users&bs ...