2

I want to able create many identical blocks with different data. For exaple list of items with different names and values.

So I have a pug file like this:

- var data = require("data.json")

mixin item(name,val)
    .item
        .item-name= name
        .item-val= val

mixin items(input)
    each itm in input
        +item(itm.name,itm.value)

+items(data)

And my JSON file data.json like this:

[
    {
        "name" : "item1",
        "value": "100"
    },
    {
        "name" : "item2",
        "value": "200"
    },
    {
        "name" : "item3",
        "value": "500"
    }
]

Also I want to load different json data and use it with my items mixin to build different blocks

But gulp didn't compile this code and throw error "write after end" on my pug file

I also added some code with "locals" for my gulp taks:

gulp.task('site:pug:pages', function() {
    var settings = Config.getTaskSettings('site:pug:pages');

    return gulp.src(BASE_PATH + settings.source)
    // return gulp.src("./html/**/*.pug")
        .pipe(plumber({
        errorHandler: notify.onError()
        }))
        .pipe(pug({pretty: true,locals: {
            require: require
          }}))
        .pipe(gulp.dest(DEST_PATH + settings.dist))
        .pipe(global.browserSync.stream());
});

But this didn't help. A know that I can pass json data from gulp task. But there are 2 issues:

  1. I don't want to pass these json at gulp task because if I have new file I should write it at gulp task file.
  2. This also didn't work and throw the same "write after end" error

Is there a easy way to use JSON data at pug templates

Graham
  • 7,431
  • 18
  • 59
  • 84

1 Answers1

0

I'm using parcel to do the job.

First get the json file on the pug.config.js file(if you don`t know about this config file look here)

const dataFile = require("./data.json");

module.exports = {
  locals: {
    dataVariable: dataFile,
  }
};

Then for exemple on a index.pug I use an each loop to display the ID's included in the someData array inside my JSON file:

each data in dataVariable.someData
  li= data.ID

data.json file used.

{
  "someData": [
    {
      "ID": "xrHLZ",
    },
    {
      "ID": "ar23D",
    }
  ]
}

LucasTelesx
  • 305
  • 2
  • 10