Leveraging Iron Router for implementing query variable settings

Utilizing Iron Router, I aim to call a page and filter the results based on the route. In this scenario, the application facilitates the creation of items. Each item contains an array that can encompass zero to multiple tags:

Item: {
  _id: <assigned by application>,
  itemTags: []
}

The dropdown list on the navbar gathers all tags from the items, performs some clean-up, and then populates them into the dropdown menu:

// HTML

<template name="header">
  <nav class="navbar navbar-default" role="navigation">
    <div class="container-fluid">
      <div class="navbar-header">
        <ul class="nav navbar-nav">
          <li class="dropdown">
            <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">Select List to View <span class="caret"></span></a>
            <ul class="dropdown-menu" role="menu">
              <li><a href="/list/all-list-items">All List Items</a></li>
              <li class="divider"></li>
              {{#each uniqueTags}}
              <li><a href="/list/{{this}}">{{this}}</a></li>
              {{/each}}
            </ul>
          </li>
        </ul>
      </div>
    </div>
  </nav>
</template>

// JS

Template.header.helpers({
  uniqueTags: function() {
    var allItems = Items.find({checked: false});
    var uniqueTags = allItems.map((function(allItems) {return allItems.itemTags;}));
    uniqueTags = _.flatten(uniqueTags);
    uniqueTags = _.compact(uniqueTags);
    uniqueTags = _.uniq(uniqueTags);
    uniqueTags = _.sortBy(uniqueTags, function (name) {return name;});
    return uniqueTags;
  }
});

The router then takes you to "/list/". Everything has been smooth sailing so far. However, it hits a snag from this point onwards. My predicament is two-fold:

1) How can I properly fetch the data context of only the items that have the specified tag included in the array?

2) How do I exhibit those items on the "list" page? I am clueless about what should be included in list.js to manage the returned data context

My existing code is provided below, but it's a bit messy and clearly not functioning :)

// JS - router.js

Router.route('/list/:tagName', {
  name: 'list',
  data: function() { 
    return Items.find({$and: [
      {checked: false}, {listItem: true}, {itemTags: {$in: ['this.params.tagName']}}
    ]});
  }
});

// HTML - list.html

<template name="list">
  <h3><span class="label label-default view-list">List</span></h3>
  {{#each listItems}}
    {{> item}}
  {{/each}}
</template>

// JS - list.js

Template.list.helpers({
  listItems: function() {
    <somehow use the returned data context>
  }
});

Thank you for your assistance!

Answer №1

Here is a possible solution

  Router.route('/list/:categoryName', {
    name: 'list',
    data: function() { 
    return { 'selectedItems' : Items.find({$and: [
          {checked: true}, {category: 'list'}, {tags: {$in: [this.params.categoryName]}}
     ]}) };
   }
  });


// HTML - list.html

<template name="list">
  <h3><span class="label label-default view-list">List</span></h3>
 {{#each selectedItems}}
   {{> item}}
 {{/each}}
</template>
 // Remember to create an item template 
// JS - list.js

Template.list.helpers({
  //listItems: function() {
  // this helper is not necessary
  // you can use the data by accessing this.data.listItems
  //<code to utilize the data context>
  //}
});

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

Top method for creating 12 dynamic product pages using AngularJS with customized routing and templates

As someone who is still relatively new to AngularJS, I am looking for advice on how to properly structure the products section of my application. My main product page will display all 12 products with clickable links to individual product pages. Each indi ...

What is the best way to handle an OR scenario in Playwright?

The Playwright documentation explains that a comma-separated list of CSS selectors will match all elements that can be selected by one of the selectors in that list. However, when I try to implement this, it doesn't seem to work as expected. For exam ...

Encountering an async issue with npm exiftool in JavaScript

I'm facing issues with npm exiftool usage. (https://www.npmjs.com/package/exiftool) I'm attempting to perform some tasks using it. Iterate through image files in a specific folder Retrieve 'xpKeywords' data of each image file Write th ...

Tips for preventing the occurrence of a final empty line in Deno's TextLineStream

I executed this snippet of code: import { TextLineStream } from "https://deno.land/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7201061632425c4341445c42">[email protected]</a>/streams/mod.ts"; const cm ...

Tips on how to optimize form input mapping without losing focus on updates

I am facing an issue with a form that dynamically renders as a list of inputs. The code snippet looks like this: arrState.map((obj,index)=>{ return( <input type="text" value={obj} onChange{(e) => stateHandler(e,index)}<inpu ...

Exploring Ways to Retrieve Depth Information within three.js

I have come across shaders that can dynamically create outlines around edges based on the difference in depth of pixels. This means that pixels with less depth compared to their adjacent pixels might have a thinner outline or none at all. Examples of such ...

NodeJS continuing to trigger setInterval() even after clearInterval() has been called

I need some help with my NodeJS script that sets and clears an interval. The starting interval works fine, but when I try to clear it, the console shows "stopping interval" yet the interval keeps firing every minute. app.get("/api", async (req, res) => ...

Looking for assistance in transferring information from one webpage to another dynamic webpage

I'm in the process of building a website to feature products using NextJs. My goal is to transfer data from one page to another dynamic page. The data I am working with consists of a json array of objects stored in a data folder within the project. Wh ...

Troubleshooting issue with jQuery datepicker not triggering onselect event

Query Function: $(function() { $("#iDate").datepicker({ dateFormat: 'dd MM yy', beforeShowDay: unavailable onSelect: function (dateText, inst) { $('#frmDate').submit(); } }); }); HTML ...

Having a quandary with Socket.io when using clients.length (where clients refers to io.sockets.clients();)

Typically, when sending JSON from one client to another, everything works smoothly. However, if there is only one client, packets are still being sent. To address this issue (on the server-side in node.js), I implemented the following solution: var client ...

Leveraging the Mutation hook for updating information on a Graphql server

Recently, I encountered an issue while utilizing the useMutation hook in React Native to update data on my server within a project I'm working on. The file where I'm implementing this hook is attached for reference. I've also included a scr ...

Translating Bootstrap 5 into Angular components for version 13 and above

In Angular, the lack of support for optional host-elements and containerless components means that each component comes with its own div wrapper. However, when designing Bootstrap components, a host-less component (without an extra div) is needed to mainta ...

Stop the unnecessary reloading of Ajax data when navigating back using the browser's back button in Chrome and Internet Explorer

I am currently designing a website where the main page showcases the latest 10 blog entries. As I scroll down and approach the end of the last item on the screen, another set of 10 blog entries automatically load through infinite scrolling. If a user clic ...

maintain ajax history during jquery redirection

Currently, I am designing a compact application using php, jquery, and ajax. The purpose of this app is to enable users to conduct customer searches, view customer details, and easily navigate back to the search page without losing any data. To enhance use ...

The values entered in the React form inputs are not displaying accurately

I'm currently working on a project that involves creating a form for tours. Everything seems to be working well, except for the issue of input values getting mixed up. For example: Actual output: { tourName: 'pune darshan', location: &apos ...

The @emit event in vue.js is not being received by the parent component

Within my application, there is a form located in the ManageCards component. This form includes a child component called ImageUpload, which emits an image file and its local URL to the parent component: <form class="mb-3"> <div class ...

Creating movement in three distinct divisions

I am seeking a way to have three divs flying in upon click. The first DIV is positioned at the top, followed by one on the left and one on the right (both being below the top one). I wish for them to fly in from their respective directions - the top div fr ...

Retrieving elements from the DOM using jQuery

UPDATE: JSFIDDLE link. My goal is to synchronize elements from DESKTOP 1 to MOBILE 1 (same for #2) in the fiddle. The error is appearing in the console. Go to DESKTOP 1 and choose NEW RATE from the dropdown list. Keep the console open to observe the issu ...

dynamically change the information in AngularJS

I need to work with two different endpoints: http://localhost:3000/entry (POST) The keys required are: fname, lname, and age. To submit a form, we have to send a POST request to this URL. http://localhost:3000/entries (GET) This endpoint will retrieve ...

Managing errors with async/await in an Angular HttpClient function

I have been experimenting with an async/await pattern to manage a complex scenario that could potentially result in "callback hell" if approached differently. Below is a simplified version of the code. The actual implementation involves approximately 5 co ...