I'm just starting out with node.js, express and ejs. And I'm having a hard time with the layout.ejs file. What I'm trying to do is something similar to what you can do in .net where you have multiple content placeholders and in the view you can have multiple blocks that go into the different placeholders.
Something like this:
<!DOCTYPE html>
<html>
<head>
<title><%- title %></title>
</head>
<body>
<%- body %>
</body>
</html>
How should my views look like?
For the given layout file, you can write a my_body.ejs file containing:
<% title = 'My Page – My Site' %>
<p>The body content could go there</p>
This will render:
<!DOCTYPE html>
<html>
<head>
<title>My Page – My Site</title>
</head>
<body>
<p>The body content could go there</p>
</body>
</html>
For a more complex header, you can also use a partial:
my_body.ejs:
<% header = partial('_header.ejs') %>
<p>The body content could go there</p>
_header.ejs:
<h1>My Page Title</h1>
layout.ejs:
<!DOCTYPE html>
<html>
<head>
<title>My Page – My Site</title>
</head>
<body>
<div id="header"><%- header %></div>
<div id="content"><%- body %></div>
</body>
</html>
Instead of
<!DOCTYPE html>
<html>
<head>
<title>My Page – My Site</title>
</head>
<body>
<div id="header"><%- header %></div>
<div id="content"><%- body %></div>
</body>
</html>
you could use
<!DOCTYPE html>
<head>
<title><%= title%></title>
</head
<html>
<%- partial('header.ejs') %>
<%- body %>
</html>
this code for your layout.ejs
the <%- body %>-tag should be defined in your "app.js" as a get-methode:
app.get('/index', function(req, res){
res.render('index.ejs', { title: 'My Site'});
});
Now you can route your index.html("index.ejs") by "localhost:PORT/index"(default Port: 3000)(type into your address-bar in your browser), the "app.js" will route the index.ejs and generates the whole code.
With the <%- partial('header.ejs') %> you can load in a snippet of your code. A Header usually should load in on every of your site(The header is static this way).
Now you have to modify all of your .ejs-files, but your layout.ejs. This means:
Your index.ejs file contains just html-tags. But no title, no doctype and so on..., just all the tags of your "Body"(from <"body"> to <"/body">).
= Your index.ejs file:
<div>
...
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With