问题
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