How can I do this type of Array in Handlebars?
I'm trying to recreate the following loop in Handlebars.
JAVASCRIPT VERSION - SAMPLE CODEPEN https://codepen.io/Len/pen/PozvRrd
As you see, it creates every combination from 2 arrays. When I tried to convert the working JS code in handlebars as a helper, I get the error ..."Uncaught TypeError: Cannot read property 'forEach' of undefined."
I tried to find a working version of this in handlebars, I've found some things but did not find the same generated results as the code pen.
My questions are below....
1 - What kind of loop is this called, when you iterate over each and every combination as you see in the output?
2 - Can someone point me to a sample of this being done in Handlebars?
Heres the code in Javascript that I'm trying to convert to Handlbars. I have oral surgery tmrw, sorry if I am slow getting back. Thanks in advance!
let arrayOne = [
1,2,3,4,5
]
let arrayTwo = [
"a","b","c","d","e"
]
arrayOne.forEach(printArrayOne);
function printArrayOne(item, index){
arrayTwo.forEach((value) => {
document.getElementById("demo").innerHTML += item + ' - ' + value + "<br>";
});
}
// OUTPUT
1 - a
1 - b
1 - c
1 - d
1 - e
2 - a
2 - b
2 - c
2 - d
2 - e
3 - a
3 - b
3 - c
3 - d
3 - e
4 - a
4 - b
4 - c
4 - d
4 - e
5 - a
5 - b
5 - c
5 - d
5 - e
1 answer
-
answered 2020-11-25 08:47
Vadim P.
It looks like the best way is to review approach and use computed data in handlebars template, but anyway, regarding to questions:
1 - It looks like a nested loop
2 - Using existing data structures it's possible to loop in the same way as in JavaScript:
{{#each arrayOne}} {{#each ../arrayTwo}} {{../this}} - {{this}}<br> {{/each}} {{/each}}
Access to iteration variables within nested block described here, in last paragraph of
#each
helper description.Example: https://jsfiddle.net/rh86gst0/
See also questions close to this topic
-
Javascript function to not load in images from a Http-source
I am new to Javascript and are trying to become better.
I was wondering how i can with the help och template-tag load the image in it if a Image is unsafe like from a http-source. Think of it like a email-client asking you if you want to load in images if not then it breaks the src. like src=temp-data, and when clicked to download and show the images then it sets the src to the correct one. here is the code i have written thus far
function removeUnsafeImgLinks(bodyContent) { let _bodyContent = bodyContent const el = document.createElement('template'); el.innerHTML = _bodyContent const nodes = el.querySelectorAll('img[src^="http://"]'); if (nodes.length > 0) { nodes.forEach((x => { x.innerHTML.replace("src=temp-data") })); } iframe.srcdoc = el.innerHTML; return newBod; }
Anyone got any tip or solution?
-
why using 'this' keyword not working while it's working with object name
I got the result at the console when calling the function with 'calculator', but it is showing undefined when using the 'this' keyword
const calculator = { calcBMI: function (mass, height) { const BMI = mass / height ** 2; return BMI; }, firstName: "Arvind", }; console.log(calculator.calcBMI(6, 1.8)); console.log(this.calcBMI(6, 1.8));
-
Is there Any way that the HREF can popup this?
Im having trouble with this thing,when it pops up as a form it works well,but when I press "Dont have an Account.." it redirects to the Parent Directory.Can someone help?Asking for a friend.
<div class="header"> <ul class="headerList"> <li id="item"> <a href="index.html">Home</a></li> <li id="item"> <a href="about-us.html" >About us</a></li> <li id="item"> <a href="contact-us.html">Contact us</a></li> <li id="popup-login"> <button onclick="togglePopup()">Login/Register</button> <div class="popup" id="popup-1"> <div class="overlay"></div> <div class="content"> <div class="close-btn" onclick="togglePopup()">×</div> <form class="form" id="login"> <h1 class="form__title">Login/Register</h1> <div class="form__message form__message--error"></div> <div class="form__input-group"> <input type="text" class="form__input" autofocus placeholder="Username or email"> <div class="form__input-error-message"></div> </div> <div class="form__input-group"> <input type="password" class="form__input" autofocus placeholder="Password"> <div class="form__input-error-message"></div> </div> <button class="form__button" type="submit">Continue</button> <p class="form__text"> <a href="#" class="form__link">Forgotten your password?</a> </p> <p class="form__text">enter code here <a class="form__link" href="./" id="linkCreateAccount">Don't have an account? Create account?</a> </p> </form>
-
Sort 2D array in Java by length of subarrays
I want to complete the following task:
You get an array of arrays. If you sort the arrays by their length, you will see, that their length-values are consecutive. But one array is missing! You have to write a method, that return the length of the missing array.
public static int getLengthOfMissingArray(Object[][] arrayOfArrays) { if(arrayOfArrays.length==0){ //array empty return 0; } for(int i=0;i<arrayOfArrays.length;i++) { //array in the array empty if(arrayOfArrays[i].length==0) { return 0; } if(arrayOfArrays[i].length!=arrayOfArrays[i+1].length-1) { return arrayOfArrays[i].length+1; } } return 0;
This works for sorted arrays. So I just need a way to order them by their length.
Is there away to sort a 2D array by the (ascending) length of its subarrays?
For example: [[1,2], [1,5,7],[4]] -> [[4], [1,2], [1,5,7]]
Arrays.sort(arr) doesnt work and I get "Ljava.lang.Object; cannot be cast to java.lang.Comparable".
-
R) Having trouble finding numbers in Arrays
a) In the lecture we created a matrix named HairEyeColor. Rename this matrix HairEyeColor1. b) Remove HairEyeColor from your Global Environment. c) In RStudio datasets, find the dataset with the name HairEyeColor. View the dataset. d) Write code to check that HairEyeColor is an array. e) Write code to determine: (i) the total number of respondents in the survey. (ii) the total number of male respondents in the survey. (iii) How many respondents have blue eyes? (iv) How many female respondents have red hair?
Above is what I was given to code, and down below is what I have tried.
# Construct a vector of the data to be used in the matrix HEC <- c(32, 11, 10, 3, 53, 50, 25, 15, 3, 30, 5, 8) # Construct the matrix HairEyeColor HairEyeColor <- matrix(HEC, nrow = 3, ncol = 4, byrow = TRUE) # fill by row # a) renaming the matrix to HairEyeColor1 HairEyeColor1 <- HairEyeColor # b) Removing HairEyeColor from Global Environment. rm(HairEyeColor) # c) view HairEyeColor. View(HairEyeColor) # d) Writing code to check that HairEyeColor is an array. is.array(HairEyeColor) # e) Writing code to determine: # (i) the total number of respondents in the survey. # (ii) the total number of male respondents in the survey. # (iii) How many respondents have blue eyes? # (iv) How many female respondents have red hair?
From c)viewing HairEyeColor, I was able to see arrays?(matrix?) with 32 rows so I tried nrow(HairEyeColor) for e)(i) but It didn't work. I also need help for other questions for e).
-
Outlook Vba - Add attachments from array
I am making an outlook macro that amalgamates draft emails (auto-created by another program) so there is one email to each recipient but with possibly multiple attachments, rather than one email per attachment.
I have an array of attachments
arrAtt()
(these attachments are from the original draft emails), an array of those attachments' corresponding email addressesarrAdd()
, and an array of unique email addressesarrUnqAdd()
. I'm creating a new email for each unique email address.Problem: My challenge is adding the Attachments straight from the array
arrAtt() As Attachment
- I get that.Attachments.Add
is only meant to work with file paths, but is there another way to add attachments straight from my array? I don't want to have to save all the files and then delete them afterwards if I can help it.Code for reference;
Dim OpenItem As Object Dim arrDraft() As MailItem 'all drafts Dim arrAtt() As Attachment 'all attachments Dim arrAdd() As String 'all email addresses Dim arrUnqAdd() As String 'unique email addresses Dim strAddrUnique As String 'unique list of email addresses, delimited For a = Application.Inspectors.Count To 1 Step -1 Set OpenItem = Application.Inspectors(a).CurrentItem If TypeOf OpenItem Is MailItem Then If OpenItem.Subject Like "*New*Invoice*" Then b = b + 1 ReDim Preserve arrDraft(1 To b) Set arrDraft(b) = OpenItem End If End If Next ReDim Preserve arrAtt(1 To UBound(arrDraft)) ReDim Preserve arrAdd(1 To UBound(arrDraft)) For a = 1 To UBound(arrDraft) arrAdd(a) = arrDraft(a).To If Not strAddrUnique Like "*" & arrDraft(a).To & "*" Then _ strAddrUnique = strAddrUnique & IIf(Len(strAddrUnique) = 0, "", "/") & arrDraft(a).To Set arrAtt(a) = arrDraft(a).Attachments.Item(1) Next arrUnqAdd = Split(strAddrUnique, "/") Dim NewMail As MailItem For a = LBound(arrUnqAdd) To UBound(arrUnqAdd()) Set NewMail = Application.CreateItem(olMailItem) NewMail.To = arrUnqAdd(a) For b = LBound(arrAdd) To UBound(arrAdd) If arrAdd(b) = arrUnqAdd(a) Then '**** 'HERE IS THE PROBLEM NewMail.Attachments.Add arrAtt(b) '**** End If Next Set NewMail.SendUsingAccount = NewAccount NewMail.Display Next End Sub
Any Suggestions much appreciated - thank you!
-
Stored Session in Laravel
I want to stored the addrId only. But I'm having trouble to get that. Below is my array;
"customerInfo" => array:1 [▼ "accountList" => {#1810 ▼ +"511000000012015": array:1 [▼ 0 => {#1821 ▼ +"accountBasicInfo": {#1761 ▶} +"contactPersonInfo": {#1817 ▼ +"contactPersonId": "511000000005007" +"addressInfo": {#1818 ▼ +"addrId": "511000000009029" +"addr1": "S" +"addr2": [] +"postalCode": "16390" } } } ] +"511000000012023": array:1 [▶]
Here is my code. The getResp are calling from API.
/** Initial Response */ $accountList = $addrList = []; $response['accountList'] = $accountList = $getResp->data; session()->put('customerInfo.accountList', $accountList);
I'm trying todo like this one, but it wont work. How can I solve it? Currently the addressInfo just return for 511000000012015 but not the next one. I'm stuck to get the session. Please help. Thank you
foreach(session()->get('customerInfo.accountList') as $keys => $addrList) { session()->put('customerInfo.addressInfo.addressID', $addrList[0] ->contactPersonInfo->addressInfo->addrId); }
-
Argsort a 2D array by its 2D coordinates
Given a 2D array, how to argsort its elements and obtain a list of the coordinates of the array elements from the lowest to highest.
For example, given:
1 5 2 3
We get:
[[0,0], [1,0], [1,1], [0,1].
Could we generalize it to
n
dimensional arrays? -
Matrix summation (Array sums by rows and columns) [Improved solution for the problem @subhra_edquart asked]
@subhra_edquart asked a question like this
"I have some array of objects and I need to calculate the total value of each row and total values of each column and finally I will add new key to each object using Javascript. I am explaining my code below."
{ BranchName: 'Deeksha, Thanisandra, Bengaluru', Uniform: 2, Shoes: 1, Accessories: 1, Books: 5, }, { BranchName: 'Deeksha, Thanisandra, Bengaluru', Uniform: 2, Shoes: 3, Accessories: 4, Books: 5, } ]
"Here I need to add one more column i.e-Grand total to each row and this should contain the sum of all key value rather than BranchName. Similarly again I need to append one more new record as last row and it should contant total value of each column. I am giving my sample output below."
@Craig Wayne wrote a solution which I used in my problem which i had afew days ago but I made improvements to make the code dynamic and flexible enough as show below
function verticalAndHorizontalSum (data, newGroupByKey, newKeys) { data = [...data] if (newKeys && newKeys.length > 0) { let keysToKeep = newKeys const sliceArray = array => array.map(o => keysToKeep.reduce((acc, curr) => { acc[curr] = o[curr] return acc }, {}) ) data = sliceArray(data) } let keys = newKeys || Object.keys(data[0]) let groupBy = newGroupByKey || keys[0] let Columntotals = { [groupBy]: 'Grand total' } //remove first element keys.shift() let columns = keys data.forEach(b => { let total = 0 columns.forEach(i => { if (b[i] === undefined) { Columntotals[i] = 0 return } Columntotals[i] = Columntotals[i] || 0 Columntotals[i] += b[i] total += b[i] }) b.total = total }) // Calculate total for Columnstotals columns.forEach(i => { Columntotals.total = Columntotals.total || 0 Columntotals.total += Columntotals[i] }) // Adding Columntotals to the Array data.push(Columntotals) return data } let data = [ { name: 'gvh a', male: 2, female: 1 }, { name: 'gvh b', male: 2, female: 1 }, { name: 'gvh c', male: 6, female: 3 } ] data = verticalAndHorizontalSum(data, 'name', ['name', 'male', 'female']) //data = verticalAndHorizontalSum(data, 'name', ['name', 'male', 'female']) console.log('Data', data) console.table(data)
-
How to show JS variable in bigcommerce handlebar?
<script> var x = "i am the value"; </script> <a href="{{url}}" class="breadcrumb-label" itemprop="item"><span itemprop="name">x is : {{x}} </span></a>
I think x should show some output but it is displaying empty when rendering. anyone can tell me how can I show the js variable in bigcommerce handlebar template
-
Issue with hosting node JS and Atlas project i heroku
My project is perfectly running in local host . But wen hosted i heroku , it gives handlebar partial could not be found error. In app.js
app.engine( 'hbs', hbs( { extname: 'hbs', defaultLayout: 'layout', layoutsDir: __dirname + '/views/layouts/', partialsDir: __dirname +'/views/partials/' }} ) );
In layout.hbs
<body> {{#if admin}} {{>admin-header}} {{/if}} {{#if vendorlog}} {{>vendor-header}} {{/if}} {{#if customerlog}} {{>customer-header}} {{/if}}
Folder structure
layouts layout.hbs
partials customer-header.hbs
-
Authenticating users if they have a cookie
I need assistance with letting users access a page (.hbs) if they have a cookie. I have listed an image of my file hierarchy with my files and some of my code. If you could provide any insight or assistance that would be very helpful.
I am trying to create an account registration and login system in which data goes into a MySQL Database. I already have the data saving properly in my database, I just need help redirecting to the dashboard page after registering / logging in.
Image of my hierarchy / files (PLEASE VIEW)
page.js (Under routes folder)
// Express Setup const express = require('express'); const router = express.Router() // Login (Main) Page router.get('/', (req, res) => { res.render('index'); }); // Login Page router.get('/login', (req, res) => { res.render('login'); }) // Register Page router.get('/register', (req, res) => { res.render('register'); }); // Dashboard router.get('/dashboard', (req, res) => { res.render('dashboard'); }) module.exports = router;
auth.js (Under routes folder)
// Express Setup const express = require('express'); const router = express.Router() // Misc const authController = require('../controllers/auth') // Auth / Register router.post('/register', authController.register); // Auth / Login router.post('/login', authController.login); // Auth / Dashboard router.post('/dashboard', authController.dashboard); module.exports = router;
auth.js (Under controllers folder)
// Database const mysql = require('mysql'); const jwt = require('jsonwebtoken') const bcrypt = require('bcryptjs') // Misc // Get Database const db = mysql.createConnection({ host: process.env.DATABASE_HOST, user: process.env.DATABASE_USER, password: process.env.DATABASE_PASSWORD, databse: process.env.DATABASE }); // Get Login exports.login = async (req, res) => { try { const { email, password } = req.body; if ( !email || !password ) { return res.status(400).render('login', { message: 'Please enter all fields.' }); } // Find User db.query('SELECT * FROM users WHERE email = ?', [email], async (err, results) => { if ( !results || !(await bcrypt.compare(password, results[0].password))) { res.status(401).render('login', { message: 'Information is invalid' }); } else { const id = results[0].id; const token = jwt.sign({ id: id }, process.env.JWT_SECRET, { expiresIn: process.env.JWT_EXPIRES_IN }); const cookieOptions = { expires: new Date( Date.now() + process.env.JWT_COOKIE_EXPIRES * 24 * 60 * 60 * 1000 ), httpOnly: true } res.cookie('loginC', token, cookieOptions); res.status(200).redirect('dashboard'); (Apart of my issue) } }); } catch (err) { console.log(err); } } // Users Page (Where I'm somewhat confused at. I want them to access this dashboard page if they have the cookie.) exports.dashboard = (req, res) => { if ( res.cookie.user == 'loginC' || id ) { res.render('dashboard') } else { res.status(401).redirect('register') } } // Run Register Module exports.register = (req, res) => { console.log(req.body); // Body Variable(s) const { name, email, password } = req.body; // Database Query db.query('SELECT email FROM users WHERE email = ?', [email], async (err, results) => { if (err) { console.log(err); } if ( results.length > 0 ) { return res.render('register', { message: 'That email has already been registed.' }); } // Hashing Passwords let hashedPass = await bcrypt.hash(password, 8); console.log(hashedPass); db.query('INSERT INTO users SET ? ', {name: name, email: email, password: hashedPass}, (err, results) => { if (err) { console.log(err); } else { return res.render('login', { message: 'User Registered' }); } }) }); }
Please note, I don't want users to have the ability to go to www.DOMAINNAME.com/dashboard without having the cookie.
If you have any questions, please let me know.