Exploring the functionalities of the modulus operator in Handlebars

I am looking to implement a solution that involves adding a div container holding 4 images based on the JSON data provided below:

var pictures = [
      {img_path: "1/1.jpg"},
      {img_path: "1/2.jpg"},
      {img_path: "1/3.jpg"},
      {img_path: "1/4.jpg"},
      {img_path: "1/5.jpg"},
      {img_path: "1/6.jpg"},
      {img_path: "1/7.jpg"},
      {img_path: "1/8.jpg"},
      {img_path: "1/9.jpg"},
      {img_path: "1/10.jpg"}
   ];

The code snippet for my handlebar template is as follows:

<script id="gallery-template" type="text/x-handlebars-template">         
    @{{#each pictures}}
           @{{#compare @index '%' 4}}
                <div class="outer">
           {{/compare}}
            <img src="@{{img_path}}" />
            @{{#compare @index '%' 8}}
                </div>
           {{/compare}}
    @{{/each}}
</script>

Handlebars.registerHelper('compare', function (lvalue, operator, rvalue, options) {

    var operators, result;

    if (arguments.length < 3) {
        throw new Error("Handlerbars Helper 'compare' requires 2 parameters");
    }       

    if (options === undefined) {
        options = rvalue;
        rvalue = operator;
        operator = "===";
    }

    operators = {
        '==': function (l, r) { return l == r; },
        '===': function (l, r) { return l === r; },
        '!=': function (l, r) { return l != r; },
        '!==': function (l, r) { return l !== r; },
        '<': function (l, r) { return l < r; },
        '>': function (l, r) { return l > r; },
        '<=': function (l, r) { return l <= r; },
        '>=': function (l, r) { return l >= r; },
        'typeof': function (l, r) { return typeof l == r; },
        '%': function (l, r) { return l % r == 0; }
    };

    if (!operators[operator]) {
        throw new Error("Handlerbars Helper 'compare' does not recognize the operator " + operator);
    }

    result = operators[operator](lvalue, rvalue);

    if (result) {
        return options.fn(this);
    } else {
        return options.inverse(this);
    }

});

Although the initial div creation logic appears to be in place, I am encountering challenges with properly closing the div tags. The aim is to group the images in sets of 4, with appropriate closure - i.e., for a total count of 10 images, the division should be 4, 4, and 2 respectively. Feel free to suggest modifications to the JSON structure to achieve this desired outcome.

Answer №1

After some tweaking with helper functions and function calls, I was able to achieve the desired outcome:

<script id="gallery-template" type="text/x-handlebars-template">         
    @{{#each images}}

        @{{#compare @index '%' 4 @last}}
            <div class="container">
        @{{/compare}}

        <img src="@{{img_path}}">

        @{{#compare @index '!%' 4 @last}}
            </div>
        @{{/compare}}

    @{{/each}}
</script>

By introducing an additional operator !% and passing lastval to the helper function, everything came together:

'!%': function (l, r) { 
if(islast === true) 
   return true; l= l+1; 
   return l % r == 0; 
}

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

Developing a countdown timer with an initial value set by the user in an input field

Whenever I click the button, the countdown only advances by one digit before stopping. It seems that the countdown is reverting to the initial value entered in the input box. My goal is to have the initial value entered in the input field set as the starti ...

Comparison between UI Router and ngRoute for building single page applications

Embarking on a new Angular project, a single page app with anticipated complex views such as dialogs, wizards, popups, and loaders. The specific requirements are yet to be clarified. Should I embrace ui.router from the start? Or begin with ngRoute and tra ...

Struggle with Transmitting Information in Ionic 2

I have been working on an Ionic project that involves a JSON file with preloaded data. The initial page displays a list from which a user can select an item to view its content. However, I am encountering a "Response with status: 404 Not Found for URL" err ...

PHP reCAPTCHA integration with AJAX functionality

I have been attempting to integrate a reCAPTCHA into my PHP contact form using AJAX. The goal is to present the user with the reCAPTCHA challenge and allow them to input it. If the input is incorrect, an error message should be displayed without refreshing ...

What is the most efficient way to substitute text within an HTML document?

Is there a way to switch between languages on a website to replace text on multiple pages with a simple button click? What is the most efficient method for achieving this? This code snippet only changes text in the first div. Is there a way to implement a ...

What could be causing the browser to only partially display an image?

Have you encountered any issues with the browser not displaying an image fully? It seems like there may be a problem with the image download or rendering process, causing only part of the image to load. My application utilizes node and socket.io. Below ar ...

Unpacking data with c# – Exploring deserialization

When data is retrieved from the API, like the example below, how should I structure this information? { "USD":{ "satis":"11.4995", "alis":"11.4012", "degisim":"1,90" ...

Tips on entering a text field that automatically fills in using Python Selenium

One of the challenges I am facing on my website is an address input text field that gets automatically populated using javascript. Unlike a drop-down field where you can select values or a standard text field where you can manually type in information, thi ...

Invoking a function sharing the same name as a local variable

The code snippet below is causing me some trouble... var firstPlay = 1; if (firstPlay == 1) { firstPlay(); } If I remove the if statement and simply have: firstPlay(); It works fine, but for some reason it doesn't work with the if statement. ...

What could be the reason for the next.js Script tag not loading the third-party script when using the beforeInteractive strategy?

I have been trying to understand how the next.js Script tag with the beforeInteractive strategy works. I am currently testing it with lodash, but I keep encountering a ReferenceError: _ is not defined. I was under the impression that when a script is loade ...

Crockford's system for safeguarded entities

Despite the abundance of questions and resources related to "Javascript: The Good Parts," I am struggling to comprehend a specific sentence in the book. On pages 41-42, the author defines the serial_maker function as follows: var serial_maker = function ( ...

Enhance your date with a specific month using MomentJS

I attempted to retrieve only the Saturdays of upcoming months with: var momentDt = moment('2017-03-18').add(1); //or 2 or 3 However, adding 1 results in April 18, 2017, which is a Tuesday. Is there an easier way in moment to achieve this wit ...

Combining AngularJS and jQuery resulted in an error: TypeError - attempting to read a property 'then' of undefined

Trying to troubleshoot a JavaScript problem, but I'm hitting a roadblock - see below for the error trace. TypeError: Cannot read property 'then' of undefined at Object.fn (angular.min.js:937) at l.$get.l.$digest (angular.min.js ...

Working with ng-model on an array with multiple dimensions

Currently, I am working on storing data in AngularJS. My table consists of various sections, rows, and columns. In each field, there is a dropdown list with the options "O", "T" or "E". My goal is to store these values in an array format: [section][row][c ...

Converting a List to JSON Attributes using JsonConvert

I need to convert an object that has a list property into a JSON object. However, I don't want the list property to be directly parsed. Instead, I want the items in the list to be added to the JSON object as properties with custom names and index suff ...

Utilizing AJAX in Yii2 to fetch data values

I have a field called _form.php <?php $form = ActiveForm::begin(); ?> <?= $form->field($model, 'IdKaryawan')->widget(Select2::classname(), [ 'data' => $listData, 'options' => [&apo ...

retrieveValue() for SelectionDropdown

I have a simple task - I just need to retrieve the name of the Company and store it in the database. Initially, I was able to achieve this using plain text and the code snippet below: sport: this.refs.company.getValue(), which worked perfectly. However, ...

Efficiently writing to response from MongoDB in JSON format without blocking the execution

My current setup involves using Node/Express.js to create a GET route that fetches data from a Mongo database. While I have successfully implemented this in a non-blocking manner, I encounter a syntax error when attempting to return the data in JSON format ...

Tips on incorporating dynamically appended table rows from javascript post button click in asp.net

After dynamically adding rows based on the selected number, I am facing issues with retrieving data from these rows when trying to submit it to the database. Upon Button Click, only the header row predefined in the HTML file is returned. Is there a way to ...

Transform your JSON data into YAML with ease. Converting JSON to YAML is a

I'm currently dealing with configuration files and need to convert JSON data into YAML format. Here is an example of the JSON file I am working with: { "foo": "bar", "baz": [ "qux","quxx"], " ...