ericf / express-handlebars

A Handlebars view engine for Express which doesn't suck.
BSD 3-Clause "New" or "Revised" License
2.31k stars 382 forks source link

How to render only a partial #145

Open brendanw opened 8 years ago

brendanw commented 8 years ago

I have a dropdown that may be reused within several pages. I have put the code for that dropdown inside of a partial because I want to be able to update the options in the dropdown without re-rendering the whole page.

partials/region-dropdown.handlebars:

    <select class="region" name="region" id="region">
      {{#each regionList}}
        <option value="{{@index}}">{{this}}</option>
      {{/each}}
    </select>

When I first load the view and layout that holds this partial, the regionList is populated correctly. This is the code I use for initially rendering the page:

      res.render('exit-selector', {
        countryList : countries,
        regionList : regions,
        NavItems : [
          { name : "Home", path : "/" },
          { name : "About", path : "/about" },
          { name : "Team", path : "/team" },
          { name: "Browse Exits", path : "/exits" }
        ]
      });

I have a jquery ajax call that occurs whenever the country dropdown on that page changes, it is supposed to update the options within the dropdown within region-dropdown.handlebars only. I try to re-render this partial with the following code:

/** Load Partial */
app.get('/region-dropdown', function(req, res) {
  res.render('partials/region-dropdown',
      {
        layout : false,
        data : {
          regionList : ["Austria", "Switzerland"]
        }
      }
  );
});

However, what is rendered is just the partial without any options. It does not look like the regionList data is successfully passed to the partial.

I am pretty new to web development and have been struggling for many hours trying to make this work. Please let me know if I am going about this the right way or if there is a small tweak that will make this work.

trideepgogoi commented 8 years ago

Try adding {{log this}} to your template. That will console.log the data that the template received. That might get you started.

http://handlebarsjs.com/builtin_helpers.html for more details.

wwwizzarrdry commented 6 years ago

Your context is different on the partial update. Wouldn't you need to reference data.regionList in your template?

Your initial call has a context of:

{
    countryList : countries,
    regionList : regions,
    NavItems : [
          { name : "Home", path : "/" },
          { name : "About", path : "/about" },
          { name : "Team", path : "/team" },
          { name: "Browse Exits", path : "/exits" }
     ]
}

Your update context is:

data: {
    regionList : regions
}

Why not just pass your updated context without the data property:

{
    regionList : regions
}