Nunjucks: Retrieve data from variables in json file (npm only)

天大地大妈咪最大 提交于 2019-12-12 06:38:19

问题


I posted a similar question recently but did not get enough of a response to understand my problem. It seems like a question that gets asked a lot but never really answered properly.

Using npm only (no gulp or grunt) with nunjucks how do you access the variables you define in a json file for use in your views when precompiling?

Scenario:

VIEWS
view1.njks: <h1>{{var1}}
view2.njks: <h1>{{var1}},  <h2>{{var2}}
view3.njks: <h1>{{var2}}

DATA
variables.json: var1: red, var2: blue.

CONFIG
app.js: path to variables.json and ability to access data globally in any view, block etc.

Hopefully this is enough info to convey my issue, please let me know if you would like me to clarify anything.


回答1:


For anyone that may come across this the solution, add

data_variable: require('../data.json')

to your route in the index.js file for each page of your site that needs data from a json file.

eg.

/* GET view1. */
router.get('/view1', function(req, res) {
        res.render('view1.njk', {
             data_variable: require('../variables.json')});
});


来源:https://stackoverflow.com/questions/41800188/nunjucks-retrieve-data-from-variables-in-json-file-npm-only

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!