ejs include function can not find the template with html extension - node.js

My ejs engine set up is app.js is like below:
// this parse html file as ejs file
app.engine('.html', require('ejs').__express);
app.set('view engine', 'html');
app.set('views', __dirname + '/view');
My directory is like this:
view (folder)
home.html
head.html
app.js
Home.html is like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>home</title>
<% include head %>
</head>
<body>
</body>
</html>
and head.html is like this:
<link rel="stylesheet" type="text/css" href="css/main.css">
<script type="text/javascript" src="js/jquery-1.5.js"></script>
the problem is the file head.html will not be parsed if the extension was html. Error says it expect ejs file. So there is a problem with include function?

As Elie Gnrd is suggesting, you use .ejs files directly by changing the view engine configuration of Express.
If that isn't an option, and you want/need to keep using .html as an extension for your templates, you have to be explicit in the include:
<% include head.html %>

You can use .ejs files directly by using app.set('view engine', 'ejs'); and renaming index.html to index.ejs.
Here is an example:
http://robdodson.me/blog/2012/05/31/how-to-use-ejs-in-express/

arrr ;)
you did not mention what app - so I assume Express >=3
solution : forget the dot and __express in
app.engine('.html', require('ejs').__express);
It should read :
app.engine('html', require('ejs').renderFile);

change html file with ejs
-view
--home.ejs
--head.ejs
-app.js
set app view engine like
app.set('view engine', 'ejs');
make index.ejs for main file and include home.ejs and head.ejs in index.ejs
<%- include('head')%>;
<%- include('home')%>;
and render it app.js like
app.get('/', (req, res) => {
res.render('index');
});
cmiiw..

I too had this problem and modified this file of my app:
myapp/node_modules/ejs/lib/ejs.js
The function is:
function resolveInclude(name, filename) {
var path = join(dirname(filename), name);
var ext = extname(name);
if (!ext) path += '.ejs';
return path;
}
You can change the default extension or as in my case I changed the function to a more direct:
function resolveInclude(name, filename) {
return join(dirname(filename), name) + '.html';
}
They can modify the function as they wish.
I hope that is helpful.

Related

express remove prefixed URL to public folder

Even though i have created static public folder in app.js
when i navigate to "http://localhost:3000/calenders/add" and i don't get any styles which is in public folder. because express has added "calenders/add/" to the public folder URL.
So it looks like "http://localhost:3000/calenders/add/content_inside_public".
But the correct URL should be "http://localhost:3000/content_inside_public"
Navigate to app index works fine and load all the styles.
Of course i can set static path in app.js like this
app.use('/calenders/add',express.static(__dirname + '/public'));
but it's not practical if i have many routes in my app.
I believe this is happening because i have a separated folder called partials inside the view directory to store headers,footers and navigation bar, so that i can include them any where in the app easily without writing same html code again and again.
This is how i included them in calender/add.ejs
<!DOCTYPE html>
<html>
<% include ../partials/head.ejs %>
<body>
<!-- Side Navbar -->
<% include ../partials/side_nav.ejs %>
<div class="page">
<!-- navbar-->
<% include ../partials/header.ejs %>
<% include ../partials/footer.ejs %>
</div>
</body>
</html>
This is how i have access the folders and style-sheets inside the public directory in headers.ejs and footers.ejs
<script src="vendor/jquery/jquery.min.js"></script>
<script src="vendor/popper.js/umd/popper.min.js"></script>
<script src="vendor/bootstrap/js/bootstrap.min.js"></script>
<script src="js/grasp_mobile_progress_circle-1.0.0.min.js"></script>
<script src="vendor/jquery.cookie/jquery.cookie.js"></script>
<script src="vendor/chart.js/Chart.min.js"></script>
This is my project structure.
/public
/css
/js
/vendor
.......
/routes
calendars.js
control_panel.js
index.js
/views
/calendars
add.ejs
/control_panel
index.ejs
calendars.ejs
/partials
header.ejs
footer.ejs
......
index.ejs
Here is the app.js
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.static(__dirname + '/public'));
app.use('/', index);
app.use('/users', users);
app.use('/control_panel', control_panel);
app.use('/calenders', calenders);
Calendars.js
router.get('/add', function(req, res, next) {
res.render('calenders/add', { title: 'Express' });
});
control_panel.js
router.get('/', function(req, res, next) {
res.render('control_panel/index', { title: 'Express' });
});
This has nothing to do with express,
this is because in /calenders/add, src of <script src="vendor/jquery/jquery.min.js"></script> will resolve to http://localhost:3000/calenders/add/vendor/jquery/jquery.min.js,
because vendor/jquery/jquery.min.js is a relative path.
what you need is to change the url to this:
<script src="/vendor/jquery/jquery.min.js"></script>
<script src="/vendor/popper.js/umd/popper.min.js"></script>
<script src="/vendor/bootstrap/js/bootstrap.min.js"></script>
<script src="/js/grasp_mobile_progress_circle-1.0.0.min.js"></script>
<script src="/vendor/jquery.cookie/jquery.cookie.js"></script>
<script src="/vendor/chart.js/Chart.min.js"></script>

ejs include doesn't work with subfolders

I am using express and ejs to build a website:
"dependencies": {
"ejs": "^2.5.2",
"express": "^4.14.0",
in my app.js I have defined ejs as template engine and the root of views:
app.set('view engine', 'ejs'); // set view engine
app.set('views', 'app/views'); // set custom root for view engine
I then created my index.ejs file in which I included a partial from a subdirectory:
index.ejs
<head><% include ./partials/template/head %></head>
folder structure:
- views
index.ejs
-- partials
-- -- template
head.ejs
When a start the server, index is loaded without errors but without the head section.
If I change the include (pointing to a wrong location) the server fails to start highlighting the problem, so ejs is able to locate the head.ejs.
if I move head.ejs in the views directory the head is correctly loaded in the index.ejs.
So... I am a bit puzzled, it seems that in the subdirectory the file read but not loaded into the include.
After searching for around I tried using express-partials but it has not helped much.
Any clue?
Cheers, Giovanni
just change your include statement like this
<%- include("./partials/template/head.ejs") %>
this worked for me.
With Express 4.0
<%- include header.ejs %>
this worked for me.
I've never used an EJS template in <head> section.
I use ejs and express-ejs-layouts packages together.
So if you want to create a top division which would be fixed and appears on every different page (maybe a navigation part), you might create a main layout ejs for your application.
When I render an EJS on a route by using res.render('index'), rendered EJS page (index.ejs in my case) replace with <%- body %> parts in the example below.
And I use a navbar.ejs file with <% include navbar %> line. And the navbar is shown on the top of the page at every page, fixedly.
Example
app.js - needed variables, settings and middleware
var express = require('express')
var expressLayouts = require('express-ejs-layouts') // to use EJS layout
var app = express()
app.set('view engine', 'ejs');
app.set('views', __dirname + '/views');
app.use(expressLayouts) // EJS Layout.ejs
layout.ejs file:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<% include navbar %>
<%- body %>
<% include page_footer %>
</body>
</html>
with express 4.0 using "ejs-mate module
In app.js
// Khởi tạo express
var express = require('express');
var app = express();
var engine = require('ejs-mate');
var port = process.env.PORT || 3000;
// Khởi tạo public, view engine...
app.use(express.static(__dirname + "/public"));
// Sử dụng đuôi html
var ejs = require("ejs");
app.set('view engine', 'ejs');
app.engine('ejs', engine);
// Cấu hình thư mục views
app.set("views", __dirname + '/views');
// Khởi tạo Web Server
var server = app.listen(port, function () {
var host = server.address().address;
var port = server.address().port;
console.log("Example app listening at http://%s:%s", host, port);
});
app.get('/Admin', function (req, res) {
res.render('./admin/layout.ejs');
});
In layout.ejs
<html>
<head>
<%-partial('./sub-folder/header')%>
</head>
<body>
<-- -->
<h1>
buiducanh.net
</h1>
<%-partial('./sub-folder/footer')%>
</body>
</html>
I believe the problem to be not related to subfolders. If you look at your code:
<head><% include ./partials/template/head %></head>
We can see the include directive is used which will invoke the templating engine and return the html that you desire to render in your <head /> section of index.ejs.
However it doesn't get rendered simply because you forgot to include a "-", which tells it to actually print the contents into that section of html, you can also use a "=" which does the same thing only escaped.
So to fix you should edit your index.ejs as follows:
<head><%- include ./partials/template/head %></head>
Notice the inclusion of the "-" following the "<%".
Hope this helps.

How to use partials in Express.js layout?

I have a layout.ejs file that contains my site's basic boilerplate HTML markup: doctype declaration, head, body, footer, the basics...
How would I go about placing the navigation in a separate partial file and including it into this layout? Is there a particular require() or include() function for doing this?
I am using EJS view engine.
Yes.
<% include path/to/template %>
Documentation here. https://github.com/visionmedia/ejs#includes
I came across similar issue with handlebars template, working with expressjs 4.0
In my app.js:
var hbs = require('hbs');
// register path to partials
hbs.registerPartials(__dirname + '/views/partials');
Then add a partial file to your partials dir:
/views/partials/nav.hbs
You could then call it within e.g index.hbs like so:
<!DOCTYPE html>
<html>
<head>
...
</head>
<body>
{{> nav}}
...
</body>
</html>
var hbs = require('express-handlebars');
// view engine setup
app.set('view engine', 'hbs');
app.engine( 'hbs', hbs( {
extname: 'hbs',
defaultView: 'default',
layoutsDir: __dirname + '/views/layouts/',
partialsDir: __dirname + '/views/partials/'
}));
see: page templates

Express & EJS - layout.ejs not used

Im trying out EJS as a view engine with Express. It seems that my layout.ejs is not used. I have two views index.ejs and layout.ejs both in my 'views' folder. It seems that index.js is rendered but layout.ejs is not. The layout.ejs file should be including a CSS file but when the page is rendered in the browser this is not there. Any test test text that I place in the layout.ejs file is not output with the response.
Am I missing an additional configuration step?
Thanks!
My server.js code:
var express = require('express');
var app = express();
app.set('view engine', 'ejs');
app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res){
res.render('index.ejs', {title: 'EJS Engine'});
});
app.listen(8080);
In my layout.ejs I am linking to a single css file which resides in the public folder.
layout.ejs:
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<link rel="stylesheet" type="text/css" href="main.css">
</head>
<body>
<%- body %>
</body>
</html>
index.ejs
<div id="container">
index.html
</div>
Here's the module you need:
https://www.npmjs.org/package/express-ejs-layouts
Do the following:
npm install express-ejs-layouts // install the layout module from the command line
var express = require("express")
,path = require('path')
,fs = require('fs')
,expressLayouts=require("express-ejs-layouts") // add this requirement
, app = express();
app.use(express.bodyParser());
app.use(expressLayouts); // add this use()
app.use(express.static(__dirname));
Now the ejs engine should use your layout.
app.set('view options', { layout:'layout.ejs' });
Place layout.ejs into your views folder.
Alternately you can place layout.ejs into views/layouts folder and then use
app.set('view options', { layout:'layouts/layout.ejs' });
I have a similar issue. In my case I would rather use Jade but I have a requirement for a more "html" style template engine for a particular project. At first I considered express-partials or ejs-locals (as mentioned in a comment by Jonathan Lonowski) or even using html via the pipe or dot syntax within Jade templates (see here for more information about that option and this SO post). I am not able to introduce the additional dependencies for express-partials and ejs-locals into this project. These two projects do look good and might meet your needs.
If you do not want to use these projects, you can do something like the following:
views/layout-head.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>The title</title>
</head>
<body>
views/layout-foot.ejs
</body>
</html>
views/index.ejs (or any other page)
<% include layout-head %>
This is the index page - <%= title %>
<% include layout-foot %>
routes/index.js
exports.index = function(req, res){
res.render('index', { title: 'Express' });
}
This is not an optimal solution but it works. Most of my application will be a single page app and I have some other restrictions I have to work within so this works for my needs. This may not the best solution in many cases - especially if you have complex and/or changing layouts.

Can not get CSS file

My directory set up is like this :
app.js
vews
home.html
css
style.css
My home file is like this :
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="css/style.css" />
</head>
<body>
</body>
</html>
My app is like this :
var io = require('socket.io'),
url = require('url'),
sys = require('sys'),
express = require('express'),
http=require('http');
var app = express();
var server = http.createServer(app);
var socket = io.listen(server);
app.engine('.html', require('ejs').__express);
app.set('views', __dirname + '/views');
app.set('view engine', 'html');
app.get('/', function(req, res){
res.render('home');
});
app.listen(4000);
sys.puts('server running ' + 'now ' + Date.now());
The problem is when i run the app, css file can not be loaded.
Since .css files are static files you have to serve them to the clients. However, you do not serve static files as a express middleware. Add the following middleware to your express app and move the css folder under the public directory (you should create a public directory)
app.use(express.static(path.join(__dirname, 'public')));
So your final directory structure should look like this
app.js
views
home.html
public
css
style.css
And do not forget to require path module
var path = require('path')
In one of my apps, I have these relevant files in this file structure:
/
index.js
/public
/stylesheets
main.css
/views
/partials
header.ejs
The index.js includes app.use(express.static(path.join(__dirname, '/public')));
Note the /public.
The header.ejs partial includes <link rel='stylesheet' type='text/css' href='/stylesheets/main.css' />
Note the lack of public, it’s implied by the middleware.
In your example, your current directory for static files doesn’t match where you are keeping static files.
Try this:
<link rel="stylesheet" type="text/css" href="/css/style.css" />
This might solve the problem.

Resources