Nunjucks扩展指令不使用Express在单独的目录中使用模板?

时间:2016-11-09 05:47:08

标签: javascript express templating nunjucks

我正在使用我的快递应用程序设置nunjucks模板是我项目的目录结构

. nunjucks-project
  |__ api
  |__ node_modules
  |__ views
     |__ templates
        |__ layouts
           |__ default.html  
        |__ pages
           |__ home.html
        |__ partials
           |__ header.html
           |__ footer.html

这是我的app.js:

/**
 *  Author Kailash K Yogeshwar 2016
 */

var express  = require('express');
var nunjucks = require('nunjucks');
var mongoose = require('mongoose');
var path     = require('path');
var config   = require('config');

var app               =  express();
var viewRoutes  =  require("./routes/viewroutes/index");
var apiRoutes   =  require("./routes/apiroutes/index");


var dbUrl = "mongodb://localhost:27017/techblogs";

mongoose.connect(dbUrl);

mongoose.connection.on('open',() => {
    console.log("Connection successfully established")
});

mongoose.connection.on("error",(err) => {
    console.error(err);
});

//configure views
app.set('views', path.join(__dirname, "views", "templates"));
app.set('view engine', 'html');


// configure nunjucks
var env = nunjucks.configure(app.get('views'), {
    autoescape: true,
    dev: true,
    noCache: true,
    throwOnUndefined: true,
    express : app
});

console.log(JSON.stringify(env, null, 3))

app.use('/', viewRoutes);
app.use('/api', apiRoutes);

app.listen(process.env.PORT || 8080, () => {
    console.log("Server Started to listen on ",process.env.PORT || 8080);
});


module.exports = app;

这是我的default.html,home.html:

!<!DOCTYPE html>
<html>
<head>
    <title>{{title}}</title>
</head>
<body>
    {% include 'partials/header.html' %}
    {% block content %} {% endblock %}
    {% include 'partials/footer.html' %}
</body>
</html>

home.html的

{% extends "layouts/default.html" %}
{% block content %}
<h1> I am home page <h1>
{% endblock %}

我认为只有当模板位于同一目录而不是在单独的目录中时才会扩展工作我也尝试在nunjucks.configure([paths],{})中指定多个路径,但这确实有效,因为它只考虑了第一个路径休息所有路径都被添加为相对路径。

屏幕截图:

Template Not Found Error

1 个答案:

答案 0 :(得分:0)

对于任何面临这个类似问题的人,我只是将我的viewRoute中间件移到下面并导出了快速应用程序的实例,并使用中间件中的实例进行渲染。

var env = nunjucks.configure(app.get('views'), options);

var viewRoutes  =  require("./routes/viewroutes/index");
var apiRoutes   =  require("./routes/apiroutes/index");

app.use('/', viewRoutes);
app.use('/api', apiRoutes);

app.listen(process.env.PORT || 8080, () => {
    console.log("Server Started to listen on ",process.env.PORT || 8080);
});

和我的viewRoutes / index.js

var express = require('express');
var nunjucks = require('nunjucks');
var app = require("../../index");

var router = express.Router();

app.get("/", function(req, res, next){
    res.render('pages/home.html',{
        title: "Home"
    });
})

module.exports = router;