F
F
FlapJalc2018-12-27 14:30:38
Pug
FlapJalc, 2018-12-27 14:30:38

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

Then all modules are connected to index.pugthrough the include
|--pages
|----index.pug

And in gulpfile, all pugfiles 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"))
});

Everything is standard, simple, without sophisticated code.
But, now how do I make the file module1.jsonconnect to the file module1.pug, module2.jsonto 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 jsonit 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

1 answer(s)
O
Oleg, 2018-12-27
@FlapJalc

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 question

Ask a Question

731 491 924 answers to any question