Reputation: 1493
I am trying to loop through an array passed by
res.render('index', { 'listItems': list_items });
Pug
div#toDoList
.col-1
h2#user_name_heading=userName
h2#user_date_signup_heading=userDate
h2 Today's To-do List
form#toDoList_form(method="POST" action="/")
input(type='text' id="list_item" name='list_item' autofocus required placeholder="task")
button(type='submit') ADD
div.col-2
.toDoListWrap
ul
script.
each list in listItems
li=list
index.js
var express = require('express');
var router = express.Router();
let users = [];
let list_items = ['jajajajaa'];
function addNewUser(data) {
try {
users.push(
{
"fname":data.fname,
"list_name": data.list_name,
"list_date": data.list_date
}
);
} catch(e) {
console.log("Failed to add user ", e);
throw e;
}
}
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
router.post('/', function(req, res, next) {
// check post valued are true
if(req.body.fname && req.body.list_name && req.body.list_date) {
try {
addNewUser(req.body);
console.log(res.headersSent);
res.json({
"message":"Successfully signed up!",
"userName": req.body.fname,
"userDate": req.body.list_date
});
} catch(e){
// signup failed
res.json(res.status(status).json(obj), "Sign up failed...");
}
}
if(req.body.user && req.body.list_item) {
list_items.push(req.body.list_item);
console.log(list_items);
// res.json({ "list_items":list_items});
res.render('index', { 'listItems': list_items });
}
});
module.exports = router;
console.log prints the following in index.js, proof there are elements in the list_items:
[ 'jajajajaa', 'f,ksha' ]
The browser logs this error:
SyntaxError: unexpected token: identifier
Upvotes: 1
Views: 270
Reputation: 7802
Your problem is the script.
tag. That tells pug to output a <script></script>
tag in the page and then output the raw content underneath it.
Just take the script.
tag out and only this is needed in your template:
each list in listItems
li= list
This will loop as expected and create <li>
elements for each entry in listItems.
Your posted code would output this:
<script>
each list in listItems
li=list
</script>
And of course your browser can't understand pug code, that text is invalid as JavaScript.
I understand that by fixing this problem you are getting a new error.
Here is a codepen that replicates your template and it works fine for me. This is the pug code:
- var listItems = [ 'jajajajaa', 'f,ksha' ];
ul
each list in listItems
li= list
Let's now use the script tag to troubleshoot this secondary issue. Add this code in your template in order to output the value of listItems to the browser console:
script.
console.log(!{JSON.stringify(listItems)});
The !{}
sequence outputs an unbuffered code expression. The stringify will be rendered on the server into a valid JavaScript value and will test the value of listItems as it appears inside the pug template.
Upvotes: 2