What is the best way to insert a <div class="row"> every 2 items in a Vue.JS template loop?

In my model, I have an array of images' URLs of varying lengths.

I want to display 2 images per row on my page, resulting in the following layout:

<div class="row">
  <div class="col">
    <img ... />
  </div>
  <div class="col">
    <img ... />
  </div>
</div>
<div class="row">
  <div class="col">
    <img ... />
  </div>
  <div class="col">
    <img ... />
  </div>
</div>
...

However, I am struggling to conditionally add the opening and closing tags of row.

Here is the code snippet I attempted, but it's not functioning as expected:

I am utilizing Bootstrap-Vue, where b-container, b-row, and b-col correspond to

<div class="container">
and
<div class="col">
.

<b-container>
  <template v-for="(url, index) in urls">
    <template v-if="index % 2 == 0">
      <b-row :key="index">
    </template>
    <b-col :key="index">
      <p>{{ index }}</p>
      <b-img
        :src="url"
        alt="charts"
        fluid
      ></b-img>
    </b-col>
    <template v-if="index % 2 == 0">
      </b-row>
    </template>
  </template>
</b-container>

Encountered Error:

 Errors compiling template:

  tag <b-row> has no matching end tag.

  40 |      <template v-for="(url, index) in urls">
  41 |        <template v-if="index % 2 == 0">
  42 |          <b-row :key="index">
     |          ^^^^^^^^^^^^^^^^^^^^
  43 |        </template>
  44 |        <b-col :key="index">

Answer №1

To enhance the organization of your image array, consider restructuring it by utilizing a computed property that divides the array into groups of two images. You also have the option to dynamically adjust the group size to alter the number of images displayed in each row.

computed: {
   makeRows(){
     let row = [];
     let i, l, chunkSize = this.rowSize; 

     for (i=0; l=this.images.length; i+=chunkSize) {
       row.push(this.images.slice(i, i+chunkSize));
     }

     return row;
   }
}

For a demonstration, refer to this functional example utilizing an array. https://jsfiddle.net/skribe/0fvj5643/7/

Answer №2

This is one way to achieve the desired result:

 <template>
        <div v-for="url in urls">
          <div class="row">
            <div class="col">
              <p>testing</p>
            </div>
            <div class="col">
              <p>testing</p>
            </div>
          </div>
        </div>
</template>

Give it a try here: https://codesandbox.io/s/bootstrap-vue-sandbox-mpt2b

Answer №3

It seems like there is a mismatch between your opening and closing tags in the code snippet provided:

<b-container>
  <template v-for="(url, index) in urls">
    <template v-if="index % 2 == 0">
      <b-row :key="index">
    </template>
    <b-col :key="index">
      <p>{{ index }}</p>
      <b-img
        :src="url"
        alt="charts"
        fluid
      ></b-img>
    </b-col>
    <template v-if="index % 2 == 0">
      </b-row>
    </template>
  </template>
</b-container>

The issue lies in having <b-row :key="index"> without a corresponding closing tag, and </b-row> without an opening tag. To rectify this, you can adjust the structure like this:

<b-container>
  <template v-for="(url, index) in urls">
    <template v-if="index % 2 == 0">
      <b-row :key="index">
        <b-col :key="index">
          <p>{{ index }}</p>
          <b-img
            :src="url"
            alt="charts"
            fluid
          ></b-img>
        </b-col>
      </b-row>
    </template>
  </template>
</b-container>

Although I'm not familiar with vue-bootstrap, this adjustment should resolve the current error without causing any new ones.

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

Enhancing user engagement with PDF files using AngularJS to create an interactive and captivating page-turn

Anyone familiar with how to achieve a page turner effect for PDF files using Angular? I'm open to jQuery solutions as well. I've come across turn.js, which uses HTML, but I'm specifically looking for a way to implement this effect with PDF f ...

A method for highlighting duplicate rows in a DataTable by formatting them with the same color

I am currently utilizing the DataTable plugin to display rows in a table. I would like to highlight duplicate rows in the same color scheme. Can someone please assist me with this issue? In the example below, the entry for Black Winters is duplicated. I ai ...

javascript string assignment

Is it possible to conditionally assign a string based on the result of a certain condition, but for some reason, it's not working? var message = ""; if (true) { message += "true"; } else { message += "false" } console.log(message); ...

Utilizing a jQuery plugin or function with customizable options when adding elements dynamically

jQuery offers a useful feature where you can use $(document).on(...) to apply an event to newly added elements in the HTML, such as after an Ajax request. Can you provide an example of how to use this with a custom function/plugin like hoverpulse? Anothe ...

Browsers seem to only respond to the FileReader onload event on the second try

Currently I am working on implementing in-browser image processing using HTML5 and encountering a strange issue specifically in Chrome. The problem lies with the onload event handler for the File API FileReader class, as the file is only processed correctl ...

Using IF-ELSE statements in jQuery for DataTables

Is there a way to handle If else statements like method in the datatable plugin? Currently, when the 'data' variable returns a value, everything works correctly. However, if it is empty, I would like it to return either "from1" or "from2", which ...

Is it possible for me to showcase a grid or table within the div css class with the assistance of bootstrap

I need help figuring out the best way to present a large number of fields to the user effectively. I have experimented with using a datatable, but since I also have images to display, I am considering utilizing a grid instead. Here is an example of how my ...

Searching for repeated values across disparate object fields?

Inquiring about the method to utilize mongoose for identifying duplicate values across different fields. Providing a sample document for reference: { "followers": { { "_id": "5bf6d610d3a3f31a6c75a9f4" }, ...

Display all active services in a new list item using AngularJS Ionic's ng-repeat directive

I've been working on a shopping cart feature for my Ionic app and everything is coming together nicely, except for the running itemized total. By default, the items in my array are set to active:false and when selected, they switch to active:true and ...

Trouble with parsing dates in JavaScript using Moment.js

I'm retrieving dates from SQL Server that are passing through ASP.NET, and then iterating through a list of objects in jQuery to display the dates along with other data. However, regardless of the various date/time values coming from the database, the ...

The JavaScript function modifies the value stored in the local storage

I'm in the process of developing a website that requires updating the value of my local storage when certain JavaScript functions are executed. Currently, I have this code snippet: localStorage.setItem('colorvar', '#EBDBC2'); I&ap ...

Display a dialog box in jQuery UI 1.7 autocomplete when an item is selected

After implementing an autocomplete widget, I noticed that a dialog appears when an item is selected. However, I am struggling to get a specific field in the dialog to receive focus upon opening. Here is what I have attempted so far: //HTML <form actio ...

Changing the 'null' string to null in JavaScript

Within an array of objects, some keys have a value of "null" as a string that I want to convert to null. Here is the code I tried: let obj = [{ "fundcode": "DE", "fundname": "Defens", ...

Encountering an issue in next.js with dynamic routes: getting a TypeError because the property 'id' of 'router.query' cannot be destructured since it is undefined

I am working on creating a dynamic page in next.js based on the ID. Here is the basic structure of my project: File path: app/shop/[id]/page.tsx This is the code snippet: "use client" .... import { useEffect, useState } from 'react' ...

What is the best way to replace testcaferc.json browsers using the command line interface (CLI

Scenario: I am facing a situation where I aim to execute Testcafe in docker within a remote environment that necessitates running Testcafe through its command-line interface. I intend to utilize the .testcaferc file that I use for local testing to avoid m ...

Attempting to wrap my head around the implementation of callback functions in THREEJS

Below is a snippet of code taken from a THREE.JS example that functions properly. I have used this code to create my own art gallery by reverse engineering it from the three.js code. However, I am puzzled by how materialPainting1 can be utilized in the cal ...

Fetching Results from Promise

Repeatedly, this question has been asked in various forms but I still do not understand: I have a resolved promise with a value. When I console.log this object, everything appears to be functioning correctly. I can see exactly what I want to see. My setu ...

Ways to prevent users from manually inputting dates in date fields

I am currently developing an application and I need to prevent users from manually entering a date in the type=date field on the HTML page. I want to restrict users to only be able to select a date from the calendar display, which is in the format MM/DD/YY ...

Error: The command "vue" is not recognized

I am encountering an issue while trying to set up vue-cli using npm. Each time I check the version, I receive the error message -bash : vue: command not found. Despite my efforts which include uninstalling and reinstalling, as well as referring to resourc ...

Retrieving Data from Repeated Component in Angular 6

Need Help with Reading Values from Repeating Control in Angular 6 I am struggling to retrieve the value of a form field in the TS file. Can someone please assist me with this? This section contains repeating blocks where you can click "add" and it will g ...