Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript One Solution

Why are we able to write code that accesses the iteration through recipes on recipe.pug?

In recipe.pug we can access each recipe through dot notation, however I'm not sure how this is possible. For example, recipe description can be accessed with recipe.description. I've been struggling to access variables throughout this whole unit. Would appreciate some tips on how to manage this better.

'recipes' in the debug console shows the array that was destructured in index.js, but 'recipe' is undefined.

The debugging course helped, however being new to express, it is difficult to understand how to stop the app at the correct place.

1 Answer

James Crosslin
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
James Crosslin
Full Stack JavaScript Techdegree Graduate 16,882 Points

Hey Zachary, the reason we can access the data in our recipe.pug file is because when it is rendered, we're passing local variables with this bit of code:

router.get("/recipes/:id", function (req, res, next) {
  const recipeId = req.params.id;
  const recipe = recipes.find(({ id }) => id === +recipeId);

  if (recipe) {
    // 2. Pass the recipe data to the 'recipe' template
    res.render("recipe", { recipe });
  } else {
    res.sendStatus(404);
  }
});

What res.render("recipe", {recipe}); does for us is pass the matching recipe object into our view engine as a variable so that we can access it in the pug template. We get that recipe object in this bit of code const recipe = recipes.find(({ id }) => id === +recipeId); that searches for the object in data.json that has a matching id value to the one requested in the url, that is req.params.id.

These advanced topics can be really tough. Hopefully this explanation helps! If it still doesn't make sense, let me know which part and maybe we can resolve this pain point.