Answer the question
In order to leave comments, you need to log in
How to connect json file to pug file?
The project uses the following file structure:
|--modules
|----module1
|------module1.pug
|------module1.json
|----module2
|------module2.pug
|------module2.json
index.pug
through the include|--pages
|----index.pug
gulpfile
, all pug
files are compiled into html
, and added to the directorydist
gulp.task("html", function() {
return gulp.src("src/pages/*.pug")
.pipe(plumber())
.pipe(pug())
.pipe(gulp.dest("dist"))
});
module1.json
connect to the file module1.pug
, module2.json
to module2.pug
, and so on. Not a single lesson on YouTube, not a single article on Google, I could not find how to implement this. Is reading data from json
it really not in demand, and unpopular? I hope they help me here.
Answer the question
In order to leave comments, you need to log in
const fs = require( 'fs' )
const path = require( 'path' )
const data = {}
const dir = 'src/modules/'
try {
const modules = fs.readdirSync( dir )
modules.forEach( item => {
const module = path.join( dir, item )
if ( ! fs.lstatSync( module ).isDirectory() ) return
const jsons = fs.readdirSync( module ).filter( item => path.extname( item ) === '.json' )
jsons.forEach( json => {
const name = path.basename( json, path.extname( json ) )
const file = path.join( dir, item, json )
data[name] = JSON.parse( fs.readFileSync( file ) )
})
})
} catch (e) {
console.log(e)
}
// далее отправляем данные в PUG (будет глобальный объект jsons)
gulp.task("html", function() {
return gulp.src("src/pages/*.pug")
.pipe(plumber())
.pipe(pug({locals: {jsons: data}}))
.pipe(gulp.dest("dist"))
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question