Can you help please, this is most odd..
I have a custom class, that contains multiple properties, one of which is an array of arrays..
I know that the data structure is ok, because I can dump it to console.log, and app.send() results in a nicely formed array in my browser.
What's weird is that when I try to render it the data browser is correct, it's just not an array of arrays anymore, it's not an array at all, just a comma separated string...
So from
[[day,1,2,3],[day,1,2,3],[day,1,2,3]]
To
day,1,2,3,day,1,2,3,day,1,2,3
Even the outer array is gone.?
Any ideas? Is there some setting I've missed?
Thanks in Advance, Bob.
Update with some code.. app.js
app.set('view engine', 'hbs');
app.engine('hbs', hbs({
extname: 'hbs',
defaultLayout: 'layout',
layoutsDir: __dirname + '/views/layouts/',
partialsDir: __dirname + '/views/partials/',
helpers:{
json: function (context){return JSON.stringify(context); }
}
}));
app.set('views', path.join(__dirname, 'views'));
index.js
class myClass{
Name = '';
Stats = [];
constructor(name){
this.Name = name;
}
}
router.get('/', function(req,res,next){
let tmp = new myClass('Dan');
let i;
for(i = 0; i < 4; i++){
tmp.Stats.push('day',1,2,3);
}
console.log(tmp.Stats);
// res.send(tmp);
res.render('index', { title: 'Test Data', data: tmp });
});
The results are as described above, console.log and res.send both respect the array structure but render strips it to a string..?
Fortunately the array is a fixed size, so I can reconstruct it in a block, but I'd rather know what I did wrong to cause the issue in the first place..
Thanks.
With above code you are not creating an array of arrays, in fact you are creating a flat array with 16 elements. If you want to push an array on each iteration you need to do:
for (i = 0; i < 4; i++) {
tmp.Stats.push(['day', 1, 2, 3]);
}
In your template you can then access the data and do something like:
<% for(let currStat of data.Stats) { %>
<ul>
<% for(let entry of currStat) { %>
<li>
<%= entry %>
</li>
<% } %>
</ul>
<% } %>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.