Sayem
Sayem

Reputation: 6099

nunjucks: Template not found

Trying to render a nunjucks template but getting Error: template not found: email.html.

server/
  views/
     email/
       email.html
  workers/
      email.worker.js
//email.worker.js
function createMessage(articles) {
   console.log(__dirname) // /<path>/server/workers

   nunjucks.configure('../views/email/');
   return nunjucks.render('email.html', articles);
}

No idea what's wrong here.

Upvotes: 9

Views: 16395

Answers (4)

Charles HETIER
Charles HETIER

Reputation: 2068

The nunjucks templates (located under src) were not included in build folder in my case. Such a configuration in my nest-cli.json file solved my issue:

{
  "$schema": "https://json.schemastore.org/nest-cli",
  "collection": "@nestjs/schematics",
  "sourceRoot": "src",
  "compilerOptions": {
    "assets": [
      "**/*.njk"
    ]
  }
}

Upvotes: 0

1565986223
1565986223

Reputation: 6718

Had the same issue, try this if it helps. If you're using express and you have a views folder:

From nunjucks docs

var app = express();

nunjucks.configure('views', {
    autoescape: true,
    express: app
});

You can use nodejs' __dirname to resolve the path for you as

nunjucks.configure(__dirname + '/views')...

Upvotes: 9

Dian
Dian

Reputation: 470

I had same issue. I found this at the documentation:

In node, 'views' would be a path relative to the current working directory.

If you run the node server at the root directory, the template path would be server/views.

 nunjucks.configure('server/views/email/');
 return nunjucks.render('email.html', articles);

In my case, the server script is in public directory.

enter image description here

So, when i run the server from the root directory, the nunjucks configuration will look like this:

 nunjucks.configure('src/templates');
 return nunjucks.render('index.html', { name : 'Dian' });

It works.

But if I run the server from the public directory, the tempate will not found.

Upvotes: 5

hector
hector

Reputation: 86

I had the same issue my solution was using path module:

const njk = require('nunjucks');

return njk.render(path.resolve(__dirname, '../views/email/' + 'email' + '.html'), articles);

Upvotes: 7

Related Questions