I am going through various tutorials on node.js and express and cannot find what this particular part of the code is actually doing. It's for the second parameter of res.render below. The part I am unsure of is the mascots: mascots part. Is this declaring a mascots variable? I cannot find anywhere in the javascript language where this is done like this so it's confusing me as to where they got this. Of course, I am just starting to learn Javascript so it could be somewhere obvious but haven't found it yet. It looks like it's an object (b/c of the curly braces {}) but even if it is, the value of named mascots is not clear to me. Is this the array of objects they are referring to? And if so it's still very confusing to me. I could get an answer for it after searching a good bit so asking here.
app.get('/', function(req, res) {
var mascots = [
{name: 'Sammy', organization: 'DigitalOcean', birth_year: 2012},
{name: 'Tux', organization: 'Linux', birth_year: 1996},
{name: 'Moby Dick', organization: 'Docker', birth_year: 2013},
];
var tagline = "No programming concept is complete without a cute animal mascot";
res.render('pages/index', {
mascots: mascots, // this line and the one below is what I am not understanding
tagline: tagline
});
});
This particular tutorial is located here for reference: https://www.digitalocean.com/community/tutorials/how-to-use-ejs-to-template-your-node-application Nice introduction and I understand everything except these two lines.
CodePudding user response:
res.render('pages/index', {
mascots: mascots,
tagline: tagline
});
this part passes down the mascots array and the tagline string to your view pages/index and then you can access both of them from your view.
I think what's confusing you is the naming. It doesn't necessarily have to be the same name.
For example if I name it like
res.render('pages/index', {
myMascotsArray: mascots,
myTagline: tagline
});
you can access the mascots array you defined as myMascotsArray from your view.
Referring the link you mentioned they have used EJS as the templating engine where you can write javascript between the <% %> tags.
Here you can notice that mascots array is accessed in the form of myMascotsArray from the view.
<ul>
<% myMascotsArray.forEach(function(mascot) { %>
<li>
<strong><%= mascot.name %></strong>
representing <%= mascot.organization %>,
born <%= mascot.birth_year %>
</li>
<% }); %>
</ul>
