Which part of this code are jade template elements and which are JavaScript elements?
-
25-10-2019 - |
Question
What I understand is that the jade template engine has its own templating elements and it also supports some JavaScript. But in the following code I can't distinguish which one is non-JavaScript code (this is node.js + express.js):
This is the view file (index.jade):
h1= title
#articles
- each article in articles
div.article
div.created_at= article.created_at
div.title
a(href="/blog/"+article._id.toHexString())!= article.title
div.body= article.body
This is the server file (app.js):
app.get('/', function(req, res){
articleProvider.findAll( function(error,docs){
res.render('index.jade', { locals: {
title: 'Blog',
articles:docs
}
});
})
});
Can anyone help me clear this confusion?
Solution
The Jade-Lang Readme has a Code section that goes into detail about what is and isn't client side javascript.
Basically if you use code inside your template, and it's not inside a script tag, it will render the output of that javascript before it sends it to the browser. It is still javascript, but it's executed server side. Any javascript inside a script tag is just normal javascript and is sent to the browser like everything else.
As for the example you posted, the line:
- each article in articles
Translates to:
for (var article in articles) {
/* Whatever else is going on in the template */
}
Also:
a(href="/blog/"+article._id.toHexString())!= article.title
Translates (simplified) to
"<a href=\"/blog\"" + article._id.toHexString() + ">" + /* Escaped article.title */ + "</a>"
But Jade parses and renders the results before it gets sent to the browser.