如何将 Nunjucks 配置文件调用到我的主 app.js 中

问题描述

在我的 Express 4.17.1 应用程序中,我有以下模板设置(如下)。我已经阅读了关于将路由提取到他们自己的模块文件中的资料。但是,我如何将下面的 nunjucks 配置代码作为单独的文件调用到我的 app.js 中并且仍然使用我的模板过滤器?只是想整理一下。

谢谢!

App.js


const express = require('express');
const nunjucks = require('nunjucks');
const env = new nunjucks.Environment();
const path = require('path');

//...other stuff...

// VIEWS | NUNJUCKS
app.set('view engine','njk');
app.set('views',[path.join(__dirname,'views'),path.join(__dirname,'views/shared/')]);

// NUNJUCKS - CONfigURATION & CUSTOM FILTERS
function setUpNunjucks(expressApp) {
    const env = nunjucks.configure([path.join(__dirname,'views/shared/')],{
        autoescape: true,//default
        throwOnUndefined: true,//for dev testing only
        trimBlocks: true,lstripBlocks: true,noCache: false,//default
        express: app
    });

    //custom Nunjucks filter to pass back into template!
    env.addFilter('shorten',function (str,count) {
        return str.slice(0,count || 5);
    });

    //an object looper.  then do stuff with it
    //apply the following inside the template form
    env.addFilter('param',function (obj,mparam) {
        for (const [key,value] of Object.entries(obj)) {
            //example of whatever is needed...
            if (mparam == value.param) {
                return `${value.value}`;
            }
        }
    });
}

setUpNunjucks(app);

//...other stuff...

//LISTEN
const PORT = process.env.PORT || 3000;
app.listen(PORT,() => {
    console.log(`Sever started on port ${PORT}`);
});

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...