简体   繁体   中英

Nunjucks not rendering template

I have folder structure as follows:

/app
   |-routes.js
/public 
   |-index.html
server.js

Server.js looks like this:

var nunjucks = require('nunjucks');
var express        = require('express');
var app            = express();
nunjucks.configure('public', { autoescape: true, express: app });
var port = process.env.PORT || 8080; 
app.use(express.static(__dirname + '/public'));
require('./app/routes')(app); // configure our routes
app.listen(port);               
exports = module.exports = app;

app/routes.js looks like this:

module.exports = function(app) {
        app.get('*', function(req, res) {
            res.render('index.html', { awesome: 'page-title' }); 
        });
    };

public/index.html looks like this:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <base href="/">

    <title>{{awesome}}</title>

</head>
<body>
        <h1>{{ awesome }}</h1>    
    </div>
</body>
</html>

When I start up my node app and browse to localhost:8080, the page title is the string {{ awesome }} and the contains the string {{ awesome }} rather than the required "page-title". How come nunjucks is not rendering the variable into the template?

You have to split 'public' folder. What is in public, cannot be processed by nunjucks. It's static (you declared it so). Put your nunjucks template in folder eg 'views'

/app
   |-routes.js
/public 
   |css/
   |img/
/views
   |- index.html
server.js

nunjucks.configure('views', ...)

如果你在windows上使用thinkjs:你的view.js应如下所示:

export default {type: 'nunjucks',root_path: think.ROOT_PATH + '\\\\view',};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM