Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to add multiple <%- %> statements to a node.js ejs layout

Tags:

node.js

ejs

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?

like image 653
Oscar Kilhed Avatar asked Feb 25 '11 17:02

Oscar Kilhed


Video Answer


2 Answers

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>
like image 119
Olivier Amblet Avatar answered Oct 02 '22 13:10

Olivier Amblet


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>
like image 44
D. Ace Avatar answered Oct 02 '22 12:10

D. Ace