Adding an element to a list in a Meteor user interface

I am currently diving into the world of Meteor and could really use some assistance with an issue I've encountered. As part of my learning process, I am working on building a gumtree style listing website to hone my skills.

The website displays a Listings collection that showcases the most recent listings created by users (see sample code below).

My question is, how can I dynamically insert a banner ad into the list of items, similar to a sponsored item? I want a random HTML chunk to be added to the page at different points in the list every time the page loads.

I attempted to populate the results from Listings.find() into an array and then insert the ad in results_list.js, but unfortunately, it was not successful. After some research, I realized that this approach doesn't work because only a cursor is being returned, and I'm struggling to figure out a solution. My background is mostly Angular, so I'm a bit lost here.

I believe a helper function might be the key, but I'm unsure where to begin. Any guidance or pointers in the right direction would be highly appreciated.


results_list.html

<template name="resultsList">
    {{#each results}}
        {{> resultDetails}}
    {{/each}}
</template>

results_list.js

Template.resultsList.helpers({
  results: function() {
    return Listings.find({}, {sort: {submitted: -1}});
  }
});

UPDATE!

Apologies for the confusion earlier. Upon further reading, I believe I've figured it out. However, I would still appreciate your feedback on this solution, as there may be a better way to accomplish this task.

This implementation will place an ad randomly within the list (excluding the beginning and end). I plan to modify the resultDetails template to include an option for displaying the advertisement code as well.

Template.resultsList.helpers({
  results: function() {
    var searchResults = Listings.find({}, {sort: {submitted: -1}}).fetch();
    searchResults.splice(_.random(1, results.length - 1), 0, {advertisement: true});
    return searchResults;
  }
});

Answer №1

One way to approach this is by making changes to your resultDetails template.

<template name='resultDetails'>
  {{#if showBanner}}
    {{> banner}}
  {{/if}}
  ..resultDetails html..
</template>

To determine whether the banner should be shown, you can have your helper function randomize the decision:

Template.resultDetails.helpers({
  showBanner: function(){
    return Math.random()>0.98; // display the banner with a 0.02 probability
  }
});

If there are specific rules in place, such as ensuring that the banner only appears once, then you may need to implement more intricate logic based on the entire cursor. This could involve calculating the exact position within the list where the banner should appear, which may require handling in the onRendered event for resultsList.

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

When trying to print a PDF on a mobile phone using Angular 2, the window.print() function is not creating the document or allowing it to be

I've encountered an issue while using the window.print() method in Angular 2 to print a receipt (Invoice) window as a PDF. It works perfectly on PC browsers - displaying and allowing downloading of the PDF. However, the problem arises when attempting ...

Using AJAX to manipulate the document structure and execute a function

Currently, I am operating on Linux -both browser side & server side- using either Firefox 38 or 42. For more context, you can refer to this question and the GitHub project containing my GPLv3 code. The web application is not standard as it typically has on ...

Using JavaScript to cheat on a typing test by automating the typing of letters

I am currently working on a solution to simulate key presses for a typing test. My idea is to extract individual letters from the text, store them in an array, and then simulate pressing each key with a delay between each press. Below is the HTML layout o ...

Sending a batch of items through an ajax request

I am faced with a challenge where I have a collection of data stored within multiple objects. Within each object, there is an ID and a status, while the main object contains a type and form id. The issue arises when trying to post the result via ajax as ...

What is the best way to sort and organize this JSON data?

There is an array of JSON objects named events that contains fields such as eventId, eventName, and the date of the event. [{event1}, {event2}, {event3}]; The goal is to iterate through this array and filter out events that occur on the same day. The des ...

Can a scope variable be passed from a controller to a service function in Angular?

angular.module('store_locator') .constant("baseURL","http://locator.sas.dev.atcsp.co.za/api/") .service('stationsService', ['$http', 'baseURL', function($http,baseURL) { this.getStations = ...

Encountering challenges with synchronous calls in AngularJS

Two service calls need to be executed synchronously in a specific order, using promises. However, the execution is not happening as intended. Controller: vm.nominationSVC.zipping(vm.fileSelected, vm.selectedCategoryId). then(function (respons ...

Obtaining a value from within an Angular 'then' block

I have a unique issue that I haven't been able to find a solution for on StackOverflow: Within an Angular 6 service, I am trying to call a function from another service using TypeScript. Here is the code snippet: Service1: myArray: Array<IMyInte ...

Angular Firebase Count of Items in List

My current dilemma revolves around obtaining a count of items within a firebase list. Firebase details: foods randompushid title: apple, comboQuery: apple23523526(userid) Angular Code snippet: this.foods= this.firebaseDB.list(& ...

Trouble with TinyColor's isValid() function

After integrating TinyColor into my project, I encountered an issue with invalid RGB values: value = {r: 'abc', g: 'something', b: 'hello'}; To validate the color, I used an if-statement: if (tinycolor(value).isValid()) { ...

Designate the preferred location for requesting the desktop site

Is there a way to specify the location of the 'Request desktop site' option? Here is the code I am currently using: var detector = new MobileDetect(window.navigator.userAgent); if(detector.mobile() != null || detector.phone() != null || det ...

Navigate through a series of loops while decreasing the initial value in the second loop

Greetings! I am in need of assistance with creating a pair of loops that will iterate through numbers in a specific manner. Let me illustrate with an example. Consider the following loop structure: for(let i = 0; let i < 4; i++){ for (let j = ?; condi ...

Implementing an event listener within a knockoutjs custom directive

I have extensive experience as a knockout user, but I am currently struggling to achieve a specific scenario. For the past few days, I have been trying to create a system within a knockout component that allows observables to translate themselves into diff ...

Unable to retrieve options from a particular select box

Utilizing cheerio and nodejs to scrape all the countries listed on a website, I have implemented the following code: const rp = require('request-promise'); const cheerio = require('cheerio'); const options = { uri: 'https://u ...

The <tbody> element remains visible even after changing the value in a dropdown menu

I have a table where I need to hide or show specific groups of rows based on the value selected in a dropdown menu. This page is built with a master page and here is the code for my dropdown box: $(function() { $("#ddlIncomeAssement").change(function() ...

Here's a unique rewrite: "Learn how to manipulate the CSS class of a textarea element (specifically in NicEdit) by utilizing the addClass

I am currently validating a textarea using the NicEdit plugin. var getContent = nicEditors.findEditor("SubSliderDescription").getContent(); bValid = bValid && checkBlankTextArea(getContent, "SubSliderDescription") function checkBlankTextArea(o, ...

There seems to be a runtime error in the Javascript code, as an

When attempting an AJAX call to a controller from my view, I encountered a JavaScript runtime error: function expected. Here is the script in question: <script type="text/javascript> var jsonData = []; var ms1 = $('#ms ...

I am receiving an undefined response from Cheerio when attempting to fetch JSON data

My goal is to create a web scraper and I have successfully downloaded the HTML. Now, with this code snippet, I am attempting to extract the title from my HTML: fs.readFile(__filename.json , function (err, data) { if(err) throw err; const $ = cheerio.load ...

Issues with AngularJS html5Mode refreshing

Here is the setup of my router using AngularJS: var app = angular.module('tradePlace', ['ngRoute', 'tradeCntrls']); app.config(['$routeProvider', '$locationProvider', function($route, $location) { $rou ...

Substituting missing data with the string "null" using AngularJS

I am struggling to display a table in an HTML page using ng-repeat. The issue arises when most of the entries in the table are null, as I am unable to replace them with either an empty space or the string "null". I attempted to use {{ row || 'null&apo ...