handlebars-webpack-plugin icon indicating copy to clipboard operation
handlebars-webpack-plugin copied to clipboard

Accessing Data

Open abelmark opened this issue 2 years ago • 1 comments

I don't see any examples on how to access the data I am passing to the plugin. Would it be possible to get an example in the README.md and/or link to example project repos?

abelmark avatar Apr 19 '22 19:04 abelmark

Hey @abelmark, here is how i figured out how to use data and make, for example, a slider.

webpack.config.ts

new HandlebarsPlugin({
    // ... path to for example slider.json
    data: path.join(__dirname, 'src/data/slider.json'),
})

My slider.json looks like this

{
  "slider":[
    {
      "bgImage": "path/to/sampleImage1.png",
      "title": "Slide 1"
    },
    {
      "bgImage": "path/to/sampleImage2.png",
      "title": "Slide 2"
    },
    {
      "bgImage": "path/to/sampleImage3.png",
      "title": "Slide 3"
    },
    {
      "bgImage": "path/to/sampleImage4.png",
      "title": "Slide 4"
    }
  ]
}

Now i parse that data to my slider.hbs component as data

page.hbs

{{ partials/slider data=slider }}

Inside my slider component i use an each loop to iterate through my object

slider.hbs

<div id="slider">
    {{#each data}}
        <div class="slide">
          <img src={{bgImage}} />
          <h1>{{title}}</h1>
        </div>
    {{/each}}
</div>

Voila, we got a dynamic component which we could feed with different data.

Hope i could help.

heydavee avatar Jul 18 '22 08:07 heydavee