ejs 'partial is not defined' - node.js

Okay I have a mostly static homepage but I wanted to have partial views that for navigation, footer ect. I'm using ejs and it looks like this:
my controller: home.js
// Dependencies
var express = require('express');
module.exports = {
get: function(req, res) {
app.set('view engine', 'ejs');
var model = {
layout:'home',
};
res.render('home');
}
};
My views directory has nav, home and footer all .ejs
Then the actual html file stripped of text would look as following.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" >
<title>Tom Jones</title>
<!-- CSS -->
<link rel="stylesheet" href="/css/home.css" type="text/css" media="screen" >
</head>
<body>
<%- partial('nav') %>
<!--content part -->
<div id="showcontainer">
<section>
</section>
</div>
<div id="maincontainer">
<section>
</section>
</div>
</body>
</html>
The Problem
When ever I test it out I run into the error partial is not defined. I tried requiring ejs but no success.

As #Pickels said, Partial was removed in 3.x. However, the most recent version of EJS provides a mechanism for including "partials", called "include":
https://github.com/visionmedia/ejs#includes
Includes are relative to the template with the include statement, for example if you have "./views/users.ejs" and "./views/user/show.ejs" you would use <% include user/show %>. The included file(s) are literally included into the template, no IO is performed after compilation, thus local variables are available to these included templates.
The following will work as a replacement for your old partial() function. You'll need to make tweaks elsewhere to support Express 3.x completely, but for the most part this seems to work well (better actually - less code and more performant).
<% include nav.ejs %> <!-- replaces your old <%- partial('nav') %> -->
Now in ejs 3.1.x
<% include('relative_filepath'); %>
Must be replaced by
<%- include('relative_filepath'); %>

Partial was removed in 3.x. It's now up to the templating engine to provide partials.

Related

Ejs renders {} when including partials

I am using this link as reference to build a simple ejs app.
Project structure:
- views
----- partials
---------- head.ejs
----- pages
---------- index.ejs
- package.json
- server.js
server.js:
const express = require('express'),
app = express();
app.set('view engine', 'ejs');
app.use(express.json());
app.use(express.static('public'));
app.get('/', (req, res) => {
res.render('pages/index');
});
head.ejs :
<title>My Awesome Site</title>
index.ejs :
<!DOCTYPE html>
<html lang="en">
<head>
<% include ../partials/head.ejs %> <!-- commenting out this line works -->
</head>
<body class="container">
<main>
<div class="jumbotron text-center header">
<img src="/images/phbc_17.jpg">
<h2 class="page-header">Be Awesome!</h2>
<p>Visit www.myawesomesite.org</p>
</div>
</main>
</body>
</html>
Index renders as expected when I am not including head.ejs partial in it. But, with head.ejs it's rendering only {} in the browser.
What am I doing wrong?
I saw two problems.
You didn't import ejsin your server.ejs file so import is as
const ejs = require('ejs');
Your ejs syntax is a mistake so use below syntax
<%- include ('../partials/head.ejs'); %>
and this need to be inside your body tag

ejs template expression in ejs template expression (not include)

My node version is v10.2.1, express version is 4.16.0, ejs version is 2.5.7.
I want to be able to change the name of the layout at a later time.
So I routing like this:
router.get('/', function(req, res, next) {
res.render('index', { title: 'my homepage' , layout: 'basic'});
});
and index.ejs
And I wrote an include in the index like this:
<% include ./layouts/basic/header.ejs %>
Now, I want to change basic to <%= layout %> but,
<% include ./layouts/<%= layout>/header.ejs %>
causes:
Could not find matching close tag for "<%".
And,
<% include ./layouts/%><%= layout %><%/header.ejs %>
causes:
Could not find the include file "./layouts/"
How can I solve it?
I am considering that you required two header views
horizontal header
vertical header
So inside views directory I have created the respective directories.
index.ejs
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<%if(layouts=='horizontal'){%>
<%include ./horizontal/header%>
<%}%>
<%if(layouts=='vertical'){%>
<%include ./vertical/header%>
<%}%>
</body>
</html>
Here I have passed layouts variable from the routes. Hope it helps you to resolve the issue.

EJS include as wrapper

Can I include another .ejs file that will wrap the current content?
I want to have a general layout like this:
layout.js:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="header"></div>
<div id="content">
<!-- I want to "inject" my code here -->
</div>
</body>
</html>
and I want to use this template from another file, like this:
content.ejs
<% inside(layout) ? { %>
content
<% } %>
Can I do something like this?
I'm currently doing this the other way around, I call layout with a parameter include_name but it's a little inconvenient. I would like to call the relevant content.ejs which includes the generic content itself. Is this possible?
Thanks,
From EJS Documentation:
EJS does not specifically support blocks, but layouts can be
implemented by including headers and footers, like so:
<%- include('header') -%>
<h1>
Title
</h1>
<p>
My page
</p>
<%- include('footer') -%>
Although some frameworks have some facilities to deal with problem. for example Express until version 3.x had layout support and for latest versions you could use it as a stand alone npm package: express-partials
With this package in place you define a <%- body %> region in your skeleton template (layout.ejs) and when you call your desired layout (content.ejs), express will render layout.ejs with content.ejs as <%- body %> ( unless you set {layout:false} which then it only renders content.ejs):
layout.ejs
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="header"></div>
<div id="content">
<%- body %>
</div>
</body>
</html>
content.ejs
content
app.js
var express = require('express')
, partials = require('express-partials')
, app = express();
// load the express-partials middleware
app.use(partials());
app.get('/',function(req,res,next){
res.render('content.ejs')
// -> render layout.ejs with content.ejs as `body`.
})
app.listen(3000);

Include HTML blocks Using node.js

This is what I want but probably can't have:
Using node.js and express and maybe ejs, I would like to, while writing a regular HTML file in my client dir, server-side-include a template block of HTML. It would be cool also if I could pass variables into the include from the HTML document.
Sooo something like:
<!doctype html>
<html>
<head>
<%include head, ({title: "Main Page"}) %>
</head>
<body>
<% include header, ({pageName: "Home", color: "red"}) %>
...
<<% include footer%>>
</body>
</html>
Is there anyhting in node world that works like this? Or any thing that comes close and that could be maybe adapted for this functionality? I would not use it exactly in the way indicated here, but this is the functionality that I am looking for.
I have looked into jade, handlebars, ember and ejs, and ejs seems to come the closest. Maybe one of these does this already, but I am just confused about the implementation.
Any suggestions would be great!
OK I got it...
server.js
var express = require('express');
var server = express();
var ejs = require('ejs');
ejs.open = '{{';
ejs.close = '}}';
var oneDay = 86400000;
server.use(express.compress());
server.configure(function(){
server.set("view options", {layout: false});
server.engine('html', require('ejs').renderFile);
server.use(server.router);
server.set('view engine', 'html');
server.set('views', __dirname + "/www");
});
server.all("*", function(req, res, next) {
var request = req.params[0];
if((request.substr(0, 1) === "/")&&(request.substr(request.length - 4) === "html")) {
request = request.substr(1);
res.render(request);
} else {
next();
}
});
server.use(express.static(__dirname + '/www', { maxAge: oneDay }));
server.listen(process.env.PORT || 8080);
and in /www I have the following .html files:
index.html
{{include head.html}}
{{include header.html}}
<p class="well">Hello world!</p>
{{include footer.html}}
head.html
<!DOCTYPE html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width">
{{include include.css.html}}
<script src="js/vendor/modernizr-2.6.2.min.js"></script>
</head>
<body>
include_css.html
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/bootstrap.css">
<link rel="stylesheet" href="css/bootstrap-responsive.css">
<link rel="stylesheet" href="css/main.css">
header.html
<div class="well">
<h1>HEADER</h1>
</div>
footer.html
<div class="well">
<h1>FOOTER</h1>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.9.1.min.js"><\/script>')</script>
<script src="js/plugins.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/main.js"></script>
<!-- Google Analytics: change UA-XXXXX-X to be your site's ID. -->
<script>
var _gaq=[['_setAccount','UA-XXXXX-X'],['_trackPageview']];
(function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];
g.src='//www.google-analytics.com/ga.js';
s.parentNode.insertBefore(g,s)}(document,'script'));
</script>
</body>
</html>
It all comes through, even includes in includes and static content. It is all performed on html files, and in a context that feel like vanilla web authoring.
++++Oops+++++
Well I almost all of it. I forgot that I also wanted to be able to pass variables into the include from the templates. I haven't tried that yet... any ideas?
++++Update+++++
Ok I figured it out.
This discussion made it clear, i guess i just didn't know enough about how ejs worked.
I have changed index.html to begin with variable declarations:
{{
var pageTitle = 'Project Page';
var projectName = 'Project Title';
}}
and then you can call these variables from within the includes, no matter how deeply they are nested.
So for instance, index.html includes start.html which includes header.html. Within header .html I can call {{= projectName}} within the header even though it was declared inside index.html.
I have put the whole thing on github.
I would recommend nunjucks or pejs. Nunjucks is jinja-inspired, while pejs is just ejs + inheritance, block, and file support.
pejs has some issues with space chomping at the moment, but it's still pretty useful. Of the two, I prefer the separation layer that comes with nunjucks.
Jade is pretty cool and has the feature-set you're looking for, but it has a very unique syntax. References for jade: template inheritance, blocks, includes
Jade does allow server side includes of HTML blocks and any locals scoped variable will get passed to the included jade template. But the both files must be in jade syntax format not raw HTML if you want to do this.
Any variable you would like to pass can just be added to the locals object.
var express = require('express');
var app = express();
var path = require('path');
app.get("/" ,(req,res) => {
res.sendFile(path.join(__dirname+'../../templates/index.html'));
});
app.use(express.static(path.join(__dirname+'../../templates/public')));
This way you can call HTML where ever the folder that contains HTML.
if you want to include CSS and Javascript use express.static see the last
line of code

Connection-route of node.js taking wrong parameters informations

I've a problem with my node.js application.
I'm using the packages connection, connection-route, socket.io and ejs.
My application provides informations to the html page (connected via socket.io), these informations are managed by an ejs template.
When I reach a destination with a parameter, like http://localhost:5001/machine/:id2, something strange happens.
The connection route code is the following:
router.get('/machine/:mac_id', function (req, res, next) {
var mac_index = req.params.mac_id.slice(1,req.params.mac_id.length);
console.log(mac_index);
res.writeHead(200, { 'Content-Type': 'text/html' });
var str = mod_fs.readFileSync(mac_route + '/index.html', 'utf8') ;
var ret = mod_ejs.render(str, {
filename: mac_route,
title: "Machine Overview",
/* other informations */
});
res.end(ret);
}
The variable mac_route contains the path to the file index.html, which is loaded correctly.
The problem lies in the mac_index variable. On the console are printed 3 rows:
id2
unctions.js
query-1.9.1.js
The first row is obviously correct, the last 2 rows are obviously not correct, infact these are two javascript files (my file functions.js and the file for jquery jquery-1.9.1.js).
These files are included in the header of the index.html file.
HTML STRUCTURE:
header.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title> <%= title %> </title>
<link rel='stylesheet' href='/style.css' type="text/css"/>
<script src="http://localhost:5001/socket.io/socket.io.js"></script>
<script language="javascript" type="text/javascript" src="functions.js"></script>
<script language="javascript" type="text/javascript" src="jquery-1.9.1.js"></script>
</head>
<body>
<div id="header">
...
</div>
<div id="page">
index.html
<% include /header.html %>
<div id="commands">
...
</div>
<div id="main">
... code of the page, manage informations received ...
</div>
<% include /footer.html %>
footer.html
<div id="footer">
...
</div>
</div> <!-- Close the "page" div opened in the header //-->
</body>
</html>
I can't find where's the mistake.
Why the file's names are taken as parameter of the req object?
The normalized URL for those files is:
http://localhost:5001/machine/functions.js
http://localhost:5001/machine/jquery-1.9.1.js
Those match your route (/machine/:mac_id), so they will be handled by it.
Try including the connect.static middleware before your routes:
app.use(connect.static(__dirname));
(this assumes your Connect app is stored in the app variable and the JS files are in the same directory as your Node script; if not, change __dirname to point to the directory where the JS files are located).

Resources