Creating a grid layout with Handlebars

I am looking to create a grid with 10 rows and 10 columns using Handlebars. I have already set up the following template:

<script id="battlefield-tmpl" type="x-handlebars-template">
    {{#each rows}}
    <div class="battlefield__row">
        {{#each this}}
        <div class="battlefield__cell" data-row="{{this.row}}" data-col="{{this.col}}"></div>
        {{/each}}
    </div>
    {{/each}}
</script>

Next, I have included a script section:

const battleFieldTemplate = getTemplate('battlefield-tmpl');

const temp = battleFieldTemplate({
        rows: [
            [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
            [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
            [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
            [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
            [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
            [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
            [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
            [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
            [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
            [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
        ]
    }
);
document.querySelector('#battlefield').innerHTML += temp;

function getTemplate(templateId) {
    const templateString = document.getElementById(templateId).innerHTML;
    return Handlebars.compile(templateString);

Now, I am seeking to modify the template so that each cell contains both row and column indexes instead of just numbers. The challenge is generating this automatically rather than inputting each index manually.

const temp = battleFieldTemplate({
        rows: [
            [{row: 0, col: 0}, {row: 0, col: 1}, {row: 0, col: 2} and so on],

If you know how to achieve this without manual input, please share your solution. Thank you!

Answer №1

Start by displaying your original data and make sure the initial template is functioning correctly.

const getTemplate = (sel) => Handlebars.compile(document.querySelector(sel).innerHTML);
const battleFieldTemplate = getTemplate('#battlefield-tmpl');

const temp = battleFieldTemplate({
        rows: [
            [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
            [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
            [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
            [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
            [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
            [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
            [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
            [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
            [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
            [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
        ]
    }
);

document.querySelector('#battlefield').innerHTML = temp;
body {
  padding: 1em;
}

.battlefield__row {
  display: block;
  margin: 0;
  padding: 0;
  margin-bottom: 0.25em;
}

.battlefield__cell {
  display: inline-block;
  width: 1.25em;
  height: 1.25em;
  line-height: 1.25em;
  border: thin solid grey;
  margin: 0;
  padding: 0;
  text-align: center;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.1/normalize.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.7.3/handlebars.min.js"></script>
<div id="battlefield"></div>
<script id="battlefield-tmpl" type="x-handlebars-template">
    {{#each rows}}
    <div class="battlefield__row">
        {{#each this}}
        <div class="battlefield__cell">{{.}}</div>
        {{/each}}
    </div>
    {{/each}}
</script>

Next, you can modify your data structure and slightly adjust the template... Access {{row}} directly without using this..

const getTemplate = (sel) => Handlebars.compile(document.querySelector(sel).innerHTML);
const battleFieldTemplate = getTemplate('#battlefield-tmpl');

const temp = battleFieldTemplate({
        rows: [
            [ {row: 0, col: 0}, {row: 0, col: 1}, {row: 0, col: 2} ],
            [ {row: 1, col: 0}, {row: 1, col: 1}, {row: 1, col: 2} ],
            [ {row: 2, col: 0}, {row: 2, col: 1}, {row: 2, col: 2} ]
        ]
    }
);

document.querySelector('#battlefield').innerHTML = temp;
body {
  padding: 1em;
}

.battlefield__row {
  display: block;
  margin: 0;
  padding: 0;
  margin-bottom: 0.25em;
}

.battlefield__cell {
  display: inline-block;
  width: 2em;
  height: 2em;
  line-height: 2em;
  border: thin solid grey;
  margin: 0;
  padding: 0;
  text-align: center;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.1/normalize.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.7.3/handlebars.min.js"></script>
<div id="battlefield"></div>
<script id="battlefield-tmpl" type="x-handlebars-template">
    {{#each rows}}
    <div class="battlefield__row">
        {{#each this}}
        <div class="battlefield__cell" data-row="{{row}}" data-col="{{col}}">{{row}}×{{col}}</div>
        {{/each}}
    </div>
    {{/each}}
</script>

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

Issue with React hooks: Callback functions from library events (FabricJS) not receiving the updated state values

Why am I not receiving the updated state values within FabricJS events like object:modified, mouse:up, etc... even though I can set state values inside those callback functions. Upon attempting to retrieve the state value, it consistently returns the init ...

Executing multiple HTTP requests simultaneously in groups using an asynchronous for loop for each individual request

I'm currently working on running multiple requests simultaneously in batches to an API using an array of keywords. Read Denis Fatkhudinov's article for more insights. The issue I'm facing involves rerunning the request for each keyword with ...

A guide to correctly importing a Json File into Three.js

I've been working on some cool projects in Blender and wanted to showcase one using threejs. However, I'm facing an issue where the object isn't displaying properly. Can someone guide me on how to correctly load a JSON file with keyframe ani ...

Creating a centered and beautifully styled picture with a specific maximum size using React

I recently completed the development of a new website, which can be viewed at Upon inspection of the website, it is evident that the photo is not centered and appears too large on mobile phones. Despite my efforts to align it using various methods outline ...

The use of React input sliders with Hooks is a powerful

Currently, I am working on creating an input slider using React Hooks that shows the number corresponding to the slider's position. However, I have encountered a problem where the slider is not responsive when moving backwards and is very slow to resp ...

Generate a Flask template using data retrieved from an Ajax request

Struggling with a perplexing issue. I'm utilizing Ajax to send data from my Javascript to a Flask server route for processing, intending to then display the processed data in a new template. The transmission of data appears to be smooth from Javascrip ...

How can you utilize jQuery's .post() method to send information as an object?

When I send a .post() request like this var data = $(this).serialize(); $('form').on('submit', function(event) { event.preventDefault(); $.post('server.php', data, function(data) { $('#data').append( ...

How can I resolve a promise that is still pending within the "then" block?

Here is a piece of code that I have written: fetch(`${URL}${PATH}`) .then(res => { const d = res.json(); console.log("The data is: ", d); return d; }) When the code runs, it outputs The data is: Promise { <pending> ...

Protractor Error Listings

In order to improve error handling in my Protractor tests, I am exploring how to handle exceptions such as No element found using locator: and provide more informative error messages. viewCompanyDocumentPage.getAttachmentType().then(function (type) { ...

In VuePress 1.x, the functionality of using the <Content> tag with pageKey is not functioning as expected

Throughout the development process, we implemented a component that would iterate through each index.md file within a folder based on the list this.$site.pages.path. However, after upgrading to version 1.0.0-alpha.39 in order to address some other issues w ...

Tips on concealing confidential keys within a React.js application on the frontend aspect

Desperate times call for desperate measures - I am attempting to conceal a secret key within my React frontend application. While I understand the risks involved, I feel compelled to do so without any other viable options. The reason behind my actions is ...

Using multiple files in Node.js Swagger

Currently, I am working on developing an Express.js application that utilizes Swagger for endpoint definition. However, the project requirements state that I must have the capability to work with multiple swagger files, each having its own unique basePat ...

Executing ts-node scripts that leverage imported CSS modules

Is there a way to execute scripts that utilize css modules? I am currently working on a typescript migration script that I would like to execute using ts-node. The ideal scenario would be to keep the script's dependencies separate from the React comp ...

When receiving a GET response after a server crash

Question: I am sending a Get request through Ajax every second and waiting for a response from the server. However, if my application crashes and I keep sending requests every second, I only receive a server timeout error (HTTP status code 502) with no oth ...

Sorting in Java using the quick sort algorithm by reading data from a file specified by the user and storing it in an array to

Hey everyone, I'm currently working on some Java code that reads numbers from a text file (each number is on a separate line), stores them in an array, and then applies quick sort to the array. However, I'm encountering some errors in Eclipse th ...

Can Angular-Material help create a sidenav that toggles on and off?

I am struggling to create a side menu that remains closed by default on all screen sizes and always opens on top of other content. Despite my efforts, it keeps switching at widths over 960px. This is the current code for my menu: <md-sidenav is-locked ...

JavaScript does not react to a hyperlink being hovered over

As I delve into the world of Javascript, I have a seemingly basic question. I created a simple program where I am aiming to display the text message "You clicked on me, stop it!" when hovering over the hyperlink "Click Me". Can you help me figure out what ...

What is the process for obtaining all of the options from a jQuery datepicker in order to create a new datepicker with identical settings?

Is there a way to easily replicate all options of a jQuery datepicker when creating a new instance? I am trying to duplicate a table that includes 2 datepickers with different settings. For reference, you can view an example here: http://jsfiddle.net/qwZ5 ...

Unable to showcase drop-down menu as ajax output on WordPress platform

I am facing an issue with displaying the output of two drop-down boxes - one with custom taxonomy and the other with its custom post under the currently selected taxonomy. To address this, I have implemented an on-change function. However, the output is no ...

Having trouble resolving the issue with importing web3 in my React project

When it comes to importing web3 in React, I keep running into errors like the ones below (7 errors!). I've tried installing 'crypto-browserify', 'stream-http', and 'https-browserify', but nothing seems to work! If you&apo ...