Using Handlebars: Send the position of every item to a nested statement

Is it possible to pass each index or key to the nested expression in handlebars?

//Not working
    {{#each thumbs}}
        <img src="{{src}} data-large="{{../<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cfa6a2aea8aabce18fa4aab6e1bcbdac">[email protected]</a>}}" alt="">
    {{/each}}

//Working with manually passed array index
    {{#each thumbs}}
        <img src="{{src}} data-large="{{../images.2.src}}" alt="">
    {{/each}}

Experience it yourself: https://codepen.io/anything/pen/LZxwVL

Answer №1

If you're looking to accomplish this task, the lookup helper in conjunction with subexpressions is your solution.

By using the lookup helper, you can retrieve the hash of an image at a specific index within your each loop. From that object, you will then need to utilize the lookup function to access the src property. Here's how it looks in code:

{{#each this.thumbs}}
  <p>SRC: {{src}}</p>
  <p>LARGE SRC:{{lookup (lookup ../images @index) "src"}} 
{{/each}}

To see this method in action, feel free to check out the changes made in the adjusted demo link.

Answer №2

To solve this issue, I developed a custom helper method:

/**
 * An enhanced iteration method for arrays in Handlebars templates
 * It adds properties to each object: "_index" (zero-based index) and "_position" (one-based index)
 */
Handlebars.registerHelper('iter', function(context, options) {
    var fn = options.fn, inverse = options.inverse;
    var ret = "";

    if(context && context.length > 0) {
        for(var i=0, j=context.length; i<j; i++) {
            ret = ret + fn(_.extend({}, context[i], { _index: i, _position: i + 1 }));
        }
    } else {
        ret = inverse(this);
    }
    return ret;
});

This custom method appends two new members (_index, _position) to the input object. I used prefixes to avoid unintentional overwriting of existing properties.

You can utilize this template like so:

{{#each thumbs}}
    <img src="{{src}} data-large="{{../<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="543d39353331277a143f315e2874782b">[email protected]</a>}}" data-index"={{_index}}" data-position"={{_position}}" alt="">
{{/each}}

However, considering your specific case, it seems that using _position may not be necessary.

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

Can you explain the functionality of this JavaScript registration code?

I am working on an ajax/jquery 1.3.2 based sign up form and I am looking to gain a deeper understanding of how to incorporate jquery into my projects by analyzing the code line by line. Could someone provide a detailed explanation of this code and break d ...

"Streamlined" Updating with Postgres Database and JavaScript/Knex/Express Inquiry

I've implemented an update endpoint that, when a request comes in with a site name matching any entry in my job site table, it changes the status of those entries to "Pending Transfer" and clears their site location data. Here's how I achieved t ...

What is the best way to implement a delay for ajax requests triggered by onkeyup events, and then restart the delay countdown each

Is there a way to add a delay for ajax requests triggered by onkeyup and reset the delay if onkeyup is triggered again? For instance, consider this code: When a user enters data into id="fname" triggering an onkeyup event, a loading span id="loading" wil ...

Striped artifacts can be observed in the lights of A-Frame technology, with their appearance varying depending

I'm currently using A-Frame version 1.0.4 and have experimented with both spotlights (as shown in the attached image) and direct light sources. Adjusting the shadowBias to -0.0001 only minimally impacts the artifact issue. By setting shadowMapHeight ...

Pass an item along with its superclass using express

Is there a way to send an object from an express server and then check the instanceof of that object on the receiving end? I am working on integration tests for express and need to verify the instanceof of the response body. Unfortunately, it seems like t ...

Selenium - Unable to click on element at current location

I encountered an error while using Selenium for my test script. The error seems to occur randomly and is not consistently reproducible. When I run the test 10 times, it occurs about twice. The element I'm attempting to click on is clearly visible in t ...

How can I determine which component the input is coming from when I have several components of the same type?

After selecting two dates and clicking submit in the daterange picker, a callback function is triggered. I have two separate daterange pickers for SIM dates and Phone dates. How can I differentiate in the callback function when the user submits dates from ...

Stop JQuery from executing when an error is caught

Once the document is ready, I have configured: $.ajaxSetup({ "error": function (XMLHttpRequest, textStatus, errorThrown) { if(XMLHttpRequest.status == 403) { display_modal( 'Please login to continue.', &ap ...

When TypeScript compiles without errors, the resulting JavaScript file still displays issues

As a newcomer to TypeScript, I decided to experiment with custom type declarations using this straightforward code snippet. The Code Here is the script I wrote: // app.ts type Customer = { name: String, isFrequentVisitor: Boolean, } type Order = { ...

Ways to incorporate a nested table into a datatable

Currently, I am working on adding a nested table to each row of a jQuery datatable using legacy datatables. I attempted to implement the example found on datatables.net for child rows and adjusted it to fit my requirements. My goal is to have the child row ...

Exploring an Array in Javascript derived from a PHP Array

I have a PHP variable named $TillArray that contains an array. I am trying to pass this array to a Javascript function in order to display an Alert message for each item within the array. Below is the code I have been using: <script type="text/javasc ...

Tips for animating elements to move on scroll while navigating through the webpage

I came across a fascinating website that has a unique scrolling effect. As you scroll down the page, only the elements and images move while the page itself remains static, creating an interesting visual effect. I tried to replicate this on my own websit ...

Guide on sending a key to a text input field using JavaScript

How can I simulate sending a combination of keys (such as Ctrl+C or Alt+Shift) when the cursor enters an input text field using Javascript? I am not utilizing jQuery, but rather MS-Ajax. Is it achievable with MS-Ajax DOM? EDIT 1) Following @Ghostoy&apos ...

The button is converting my text to a string instead of the integer format that I require

Hello everyone, I've been grappling with this button conundrum for the last 45 minutes, and I can't seem to find a solution. I have created three different buttons in my code snippet below. (html) <div class="action"> ...

Canvas not displaying image in JavaScript

I have a bird object with a draw function defined, but for some reason, the image is not showing up when called in the render function. Can someone please help me figure out what I'm doing wrong? Thanks in advance. EDIT: Upon further investigation, I ...

Adjusting the contenteditable feature to place the caret on a specific child node

I am experiencing some challenges when attempting to position the cursor after an <i> tag within a contenteditable element. Currently, this is what I have: <p contenteditable="true"><i>H</i><i>e</i><i>l</i> ...

Send data using only Javascript

Hey there, I'm a beginner in javascript and I'm having some trouble submitting a form using pure javascript. Here is my code: var myform = document.getElementById('js-post-form'); myform.addEventListener('submit', function(e ...

Exploring the Methods to Monitor Variables in Framework7 Store

Currently, I am in the process of developing my app and have opted to utilize the new built-in store system instead of relying on Vuex. I have a variable that undergoes frequent changes and previously used the following code when working with Vuex: store.w ...

Creating a Powerful Application with Typescript and NodeJS

Currently, I am attempting to utilize Got with Typescript and ESM. With Got being written in Typescript itself, I anticipated a seamless integration. Alas, even after diligently following this comprehensive guide authored by the creator of Got, I am unable ...

submit a unidirectional post using jquery.post

I am working with a variable named test_string which is set to the value "hello." var test_string = "hello"; I want to send this variable to a PHP page in a one-way communication. I have attempted the following: $.post('php_page.php', test_str ...