What is the best way to display multiple templates using a single route controller in iron-router?


Background:

In my latest project, I am developing a blog using meteor and iron-router. The goal is to utilize a single controller for multiple "category pages" that filter a list of blog articles in the yield region.

The Problem:

One key issue I'm facing is that the article list does not refresh when the URL changes, meaning it lacks reactivity. Interestingly, when navigating back to the home page, the correct article list appears.

The Question:

I'm seeking guidance on how to update the article list dynamically when switching between different routes on the category route controller.


Example Code:

To explore the full codebase of this project, please visit this link.

Below is an excerpt from my Route Controller:

CategoryController = RouteController.extend({
    action: function(){
        this.render();
    },
    template: 'category',
    data: function(){
        return {category: this.params.category};
    }
});

CategoryController.helpers({
    articles: function(){
        return Articles.find({category: this.params.category});
    }
});

And here is the associated template it renders:

<template name='category'>
    <div class="container">
        <h2>{{category}}:</h2>
        <ul>
            {{#each articles}}
                <li>
                {{#linkTo route="article.show"}}
                    {{title}}
                {{/linkTo}} 
                </li>
            {{/each}}
        </ul>
    </div>
</template>

Resources/Updates:

  • Take a look at this informative article on Meteor Reactivity and the Deps Package. While experimenting with Deps.autorun in various sections, it seems like this may not provide the solution needed.
  • Currently exploring methods to have different "category" routes inherit from the controller.

Answer №1

The content listing remains static due to the Template helper not utilizing a reactive data source. To introduce a reactive dependency on route parameters, you can utilize the RouteController.getParams method as demonstrated below.

CategoryController.helpers({
    articles: function(){
        var controller = this;
        var params = controller.getParams();

        return Articles.find({category: params.category});
    }
});

Referencing Iron Router documentation:

Note: If you wish for a function to re-execute when the hash changes, follow these steps:

// acquire controller instance
// in a template helper, this would be
// var controller = Iron.controller();
var controller = this;

// use reactive getParams method to trigger an update if any parameter changes,
// including the hash.
var params = controller.getParams();

By default, the router adheres to normal browser behavior. Clicking a link with a hash fragment will scroll to an element with that specific id. To implement controller.getParams(), incorporate it into your custom autorun for procedural tasks or within a helper function.

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

Downloading files from a Blob in NodeJS: A step-by-step guide

How do I retrieve a file from a BLOB column using NodeJS? Currently, I am utilizing the oracledb library for database operations and my code snippet is as follows: async function getFile(req, res) { let filename = req.params.filename; let file = a ...

What is the best way to generate an @ symbol using JavaScript?

When coding in Javascript, a challenge I am facing is creating a variable that includes the @ symbol in a string without it being misinterpreted as something else, especially when dealing with URLs. Does anyone have any suggestions on how to handle this ...

Combining jqGrid with a POST request and utilizing default parameters for serializing grid data

My grid needs to be loaded from a server that requires a URL, parameters, and a serialized payload in the message body. The server expects a POST method along with JSON payload. The serialized payload is a JSON string for MongoDB that guides mongo in find ...

What is the process for extracting the "user_id" from the token payload and inserting it into the JSON POST form in Django REST with SimpleJWT and Vue3?

After storing access and refresh tokens in my local storage, I have decoded the access token and found the "user_id" in the payload. However, I am struggling to comprehend how to include this "user_id" in a POST request to the REST API. Is it retrieved fro ...

Ways to create two distinct "on click" actions for a single image to execute two distinct tasks

Clicking on an image will open a slider showing all images before filtering. Once filtered, only the selected images will be displayed in the slider. <div class="gallery row" id="gallery" style="margin:0;"> <!-- Grid column --> <div ...

Is memory allocated for 32 bits for variables with an undefined value in Javascript?

If I have a function with the signature below: function test(variable1, variable2) {} And I call it with only one parameter: test(5); Then within the test function, variable2 will be created but with a value of undefined. I'm interested to know if ...

Unable to display toast notification in React/MUI/Typescript project

Currently tackling error notifications targeted at 400,401, and 500 errors within a large-scale project. I am facing an issue where I want to integrate my ErrorToastNotification component into my layout.tsx file to avoid duplicating it across multiple page ...

terminating the Mongo server through the C# Driver API

How can I shutdown the MongoDB server from my C# application upon exiting? I have been attempting to use the RunAdminCommand method from the MongoServer object to accomplish this task. Here is a snippet of the code: MongoServer server = MongoServer.Creat ...

The functionality of toLowerCase localeCompare is restricted in NuxtJs VueJs Framework

Encountered a peculiar issue in NuxtJs (VueJs Framework). I previously had code that successfully displayed my stores in alphabetical order with a search filter. When I tried to replicate the same functionality for categories, everything seemed to be work ...

Angular Checkbox Single Select

I have a piece of HTML code with ng-repeat that includes checkboxes. <table> <tr ng-repeat="address in contactInfo.Addresses"> <td>{{address.DisplayType}}</td> <td>{{address.AddressLine1}}</td> <td>{ ...

Retrieving information using an ajax request in JavaScript

Although this question may have been asked several times before, I have yet to find a satisfactory answer. I passed a URL in an Ajax call and I am trying to retrieve data from the database through a query in the success method of the Ajax request, but for ...

Experiencing complications with an Angular 2 router

When a user logs into the system, they are greeted with a navigation bar featuring options like Dashboard, Customers, and Product. Below is an excerpt from my routes file: app.routing.ts export const router: Routes = [ { path: '', redir ...

`Async/await: Implementing a timeout after a fadeout once the fadein operation is

Here is a snippet of code that demonstrates the process: async function loadForm (data) { let promiseForm = pForm(data); await promiseForm.then(function(data) { setTimeout(function () { $container.fadeOut(function() { ...

Activate a specific table by inputting the data from a different table

I am attempting to automate the calculation of a table by inputting values from another table. There are two tables involved; the first one has an input field named profit_rate, and the second one is supposed to calculate cost * currency_rate * profit_rate ...

Incorporating Card Layouts with SwiperJS

Reference Code: See Example on Code Sandbox I am looking to implement a swiper that allows for navigating one slide at a time with a layout where slidesPerView: "auto" and fixed width are used. The first two slides behave as expected, but the la ...

An exclusive execution of the JavaScript function is ensured

I have a JavaScript function that I want to execute 12 times in a row. Here's my approach: Below, you'll find a list of 12 images: <img id="img1" src=""> </img> <img id="img2" src=""> </img> <img id="img3" src=""> ...

Storing data with just a click

Upon clicking the link <a href="http://localhost/redmine/projects/'+ value.id+'">'+ value.name+'</a>, I aim to store the value.id into the following variable: x is the variable. var x = document.getElementById(value.id).va ...

What is the best way for a client to showcase a constantly fluctuating server-side variable's value?

On my website's homepage (index.html), I want to show a dynamic server-side global variable called serverVariable. This variable is always changing based on the node.js server-side code. However, since the client doesn't know what serverVariable ...

Automatically Populate Custom Body Fields in NetSuite Using Line Item Data

As a newcomer to NetSuite scripting, I am working on populating 3 custom body fields within an Item Fulfillment form. The fields I need to populate are Line Item Name, Line Item Class, and Line Item Count (which represents the total count of line items in ...

$scope variables, ng-hide/show directive

There seems to be a confusion with $scope in my code. I have ng-hide/shows that use a variable in the top nav, controlled by "NavController". Inside an ng-view, controllers are linked via the app config function. The appointment setting functionality is ha ...