angry kiwi
angry kiwi

Reputation: 11485

ejs include function can not find the template with html extension

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?

Upvotes: 13

Views: 18786

Answers (5)

user2763596
user2763596

Reputation:

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..

Upvotes: 1

sebilasse
sebilasse

Reputation: 4618

arrr ;)

  1. you did not mention what app - so I assume Express >=3
  2. solution : forget the dot and __express in

app.engine('.html', require('ejs').__express);

It should read :

app.engine('html', require('ejs').renderFile);

Upvotes: 2

alditis
alditis

Reputation: 4827

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.

Upvotes: 1

robertklep
robertklep

Reputation: 203534

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 %>

Upvotes: 13

Elie G&#233;nard
Elie G&#233;nard

Reputation: 1683

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/

Upvotes: 1

Related Questions