简体   繁体   中英

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

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.

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')});
});

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