Unexpected identifier while compiling ejs in for loop - javascript

I'm making a for loop in ejs and get this error:
Unexpected identifier while compiling ejs
Here's my for loop
<ul class="results">
<% for (int i=0; i<results.length; i++) { %>
<li><%= results[i] %></li>
<% } %>
</ul>
express code:
app.set("view engine", "ejs")
const results = []
app.get("/", (req, res) => {
res.render("index", { results: results })
})

You used int keyword inside for loop condition. int keyword doesn't exist in JS.
<ul class="results">
<% for (let i=0; i<results.length; i++) { %> // changed int to let
<li><%= results[i] %></li>
<% } %>
</ul>

Related

I am trying to parse an array of string in Jade but always results in 404

I have been trying to parse an array of strings on my jade file but it doesn't seem to work.
I can console log the array of strings from my mongodb collection but it does not reflect on my jade.
my code: from js
(global variable) let secretstitle = [];
dbo.collection("users1").findOne({secretdocument:"rousbepistola"} ,function(err, data){
if (err) throw err;
ssn.secretpost = data.secretpost;
ssn.secrettitle = data.title;
console.log(data.secretpost);
console.log(data.title)
console.log(ssn.secretpost[0]);
console.log(data.title[0])
for(let i = 0; i < (data.secretpost).length; i++) {
secretstitle.push(data.secretpost[i])
}
console.log(secretstitle);
console.log('Yay!')
db.close();
my code: from jade
.row
each n in secretstitle;
.jumbotron.col-md-12
h1 #{n}
|
h6 January 24, 2019 08:54:05 #username
|
p
| W3Schools is optimized for learning
I am trying to create a blog type content that adds to itself indefinitely like Facebook, 9gag, or twitter. I have received the console.log("yay") on my terminal. I appreciate every help I could get. By the way, my collection looks like this:
id:ObjectId("random")
secretposts:Array
0:"post1"
1:"post 2"
3:"post 3"
title:Array
0:"title 1"
1:"Title 2"
3:"Title 3"
Somewhere in the callback from your mongodb findOne call you need to add a res.render:
dbo.collection("users1").findOne({secretdocument:"rousbepistola"} ,function(err, data){
res.render('viewname', data);
});
Without that the pug/jade engine won't call the template with the returned data.
was just able to solve it now with my jade code as follow
.row
- for (var i = 0; i < himitsupost.length; ++i) {
return
.jumbotron.col-md-12(style='background-color:lightgreen;')
h3 #{himitsutitle[i]}
h5 #{himitsupost[i]}
- }
And my js file as follows
dbo.collection("users1").findOne({secretdocument:"rousbepistola"} ,function(err, data){
if (err) throw err;
ssn.secretpost = data.secretpost;
ssn.secrettitle = data.title;
console.log(data.secretpost);
console.log(data.title)
// console.log(ssn.secretpost[0]);
// console.log(data.title[0])
secretspost = [];
for(let i = 0; i < (data.secretpost).length; i++) {
secretspost.push(data.secretpost[i])
}
secretstitle = [];
for(let i = 0; i < (data.title).length; i++) {
secretstitle.push(data.title[i])
}
console.log(secretspost);
console.log('Yay!')
db.close();
});
});
res.render('release',{username:ssn.username, himitsutitle:secretstitle, himitsupost:secretspost});

Try catching a variable passed in from res.render

I am executing a try catch block within a script tag on my ejs webpage.
My server renders the page sometimes with the token & user, and sometimes without. Each time I passed through a variable I would do the var x = <%- JSON.stringify(x) %>;. This time I did it, since there was nothing passed in, it gave me an error.
This is not the issue. The issue I am running into is that it does not seem to work! See the below code:
try {
var Token = <%- JSON.stringify(Token) %>;
var User = <%- JSON.stringify(User) %>;
}
catch(err){
console.log("there is no token/user");
}
I want for my code to try to initlize these variables, if they were passed in from the res.render function from the server. If they were not passed in, no problem, just continue on.
You can't use try/catch to detect a syntax error.
Instead, you could give a default value in case the variables aren't set.
var Token = <%- JSON.stringify(Token || "") %>;
var User = <%- JSON.stringify(User || "") %>;
if (Token == "" || User == "") {
console.log("there is no token/user");
}
var tokenexist = false;
var userexist = false;
<% if (Token) {
tokenexist = true;
}
if (User) {
userexist = true;
} %>
if (userexist && tokenexist) {
var Token = '<% - JSON.stringify(Token) %>';
var User = '<% - JSON.stringify(User) %>';
} else {
console.log("there is no token/user");
}

nodejs express sent object not synchronized with front end

I am trying to send an object from nodejs server to the front end but one property is keep getting deleted on the way
server
router.post('/cart/retrieve', (req, res) => {
let cart = req.session.cart;
let prodId = Object.keys(cart);
Product.find({_id: {$in: prodId}}, (err, result) => {
if (err) throw err;
let resultToSend = [];
for (let i = 0; i < result.length; i++) {
let curResult = result[i];
curResult['cartQuantity'] = parseInt(cart[curResult._id]);
result[i] = curResult;
}
resultToSend = result;
console.log(resultToSend[0]['cartQuantity'])
res.json({cart: resultToSend})
});
});
frontend
$("#top-cart-trigger").click(function(e){
$.post('/api/shop/cart/retrieve',{
}, function (returnResult) {
console.log(returnResult['cart'][0]['cartQuantity'])
let products = returnResult['cart'];
console.log(returnResult)
for(let i = 0; i < products.length; i ++){
let curProduct = products[i];
console.log(curProduct['cartQuantity'])
}
});
});
so practically the json variable sent from server and the returnResult received from the front end are same variables. However, my console.log(resultToSend[0]['cartQuantity']) returns 3 (which is correct) but console.log(curProduct['cartQuantity']) is undefined for all elements. What am I doing wrong?
I think the problem might comes from mutable variable result in your server.
However it seems like the variable returnResult['cart'] is JSON and you are expecting array. You could use 'for in' instead. See https://developer.mozilla.org/cs/docs/Web/JavaScript/Reference/Statements/for...in
Just try to replace for loop with this
for (let key in returnResult['cart']){
console.log(returnResult['cart'][key]['cartQuantity']);
}

Mongoose Query: inserting html separators according to object parameter

I've recently started to dive into JavaScript and NodeJS to build a project for my thesis.
I have a collection (plants) with a property for its objects (gardener: String)
It's being queried on the route:
app.get("/", function(req, res) {
Plant.find({}).sort('gardener').exec(function(err, plants){
if (err) { console.log(err); }
else {
res.render("index", {plants: plants});
}
});
});
How can I show all plants but PLACE A SEPARATOR for each gardener? (a gardener will be a user, therefore, can be limited)
Something like
<h4>Gardener <%=plant.gardener%></h4>
[here goes a list of the plants of this gardener]
For instance (rendering of /):
<h4>Gardener Mary</h4>
... (list of Mary's plants)
<h4>Gardener Joseph</h4>
... (list of Joseph's plants)
<h4>Gardener George</h4>
... (list of George's plants)
[...]
P.S.: I know the best is to define gardener as a reference for a user, but that will be the next step :)
Inside your else statement you could reorganize your plants array:
var newPlants = [];
var aux = [];
var previousGardener = "";
plants.forEach(function(plant) {
if(previousGardener === plant.gardener) {
aux.push(plant);
return ;
}
if(previousGardener !== "") {
newPlants.push({ gardener: previousGardener, plants: aux });
aux = [];
}
aux.push(plant);
previousGardener = plant.gardener;
});
if(aux.length > 0) newPlants.push({ gardener: previousGardener, plants: aux });
res.render("index", { plants: newPlants });
And your html would be something like:
<% for(var i = 0 ; i < plants.length ; i++) { %>
<h4><%= plants[i].gardener %></h4>
<ul>
<% for(var j = 0 ; j < plants[i].plants.length ; j++) { %>
<li><%= plants[i].plants[j].description %></li>
<% } %>
</ul>
<% } %>
I wrote this on the fly so apologies if something is wrong.
And happy new year as well :)

JSON returns 'Null' error... #object.to_json wrong place?

-Update-
found answer here: json, rails, parse error in javascript
also, see iltempo's answer below (thanks iltempo)
JSON / GOOGLE MAPS
PlacesController, index respond_to block
format.json { render json: #places }
places.js.erb (/assets)
var markersArray = <%= #places.to_json %>;
addMarkerArray(markersArray);
function addMarkerArray(markersArray) {
for(var i = 0; i < markersArray.length; i++) {
var lt = markersArray[i].latitude;
var lg = markersArray[i].longitude;
...
...
}
)
Firebug Error
TypeError: markersArray is null
" for(var i = 0; i < markersArray.length; i++) { "
You are not able to access the ERB template variable #places in a Javascript file placed in assets/. Instead call the function addMarkerArray() with the return value of the AJAX call you do to get the places data.

Categories