Day 3 - HTML Templates
The two popular template engines for Node/Express are Jade and EJS. Jade looks promising with some sort of interesting minimal syntax similar to:
!!! 5
html(lang="en")
body
h1 This saves a lot of keystrokes
It does seem to have a bit of potential for frustration - and it seems to compile to HTML without newlines, so I'm going to go with EJS for now.
EJS allows for HTML to be written in HTML, so what I see when debugging is what I see when writing the
'code'. It seems to have a nice concept of layouts, which let me do something like this:
layout.ejs (default name for the "global" layout)
<!DOCTYPE html>
<html>
<body>
<%- body %>
</body>
</html>
editor.ejs
<h1>I'm a document with a variable <%= foo %>.</h1>
These layouts can be nested.
Back to init.js, first we need to tell Express to use EJS when rendering pages
app.set('view engine', 'ejs');
Then, inside our editor.js response callback, we can use render instead of send:
response.render("editor.ejs", {
foo: "bar"
});
Result
<!DOCTYPE html>
<html>
<body>
<h1>I'm a document with a variable bar.</h1>
</body>
</html>
So far this looks really nice. Global variables can be accessed, and local variables can be explicitly passed through.
Tomorrow, I'll start to actually create some content to test out the template engine properly (and hopefully figure out what is going on with my MongoDB - it suddenly started working).
Just thought I'd stop by to give encouragement. Keep it up! I'm following along every day (via Google Reader), so you definitely have at least one reader. :)
ReplyDeleteThanks for great information you write it very clean. I am very lucky to get this HTML /nodejs articles from you.
ReplyDeleteSix things that you need to know about MEAN stack