2

Here is my route.

router.get("/blocks/:id", (req, res) => {
    res.render("../views/block", {
        data: data,
        blockId: req.params.id,
    });
});

Here is my view

<div class="row">
    {{#each data}}
        <div class="col">
            <div class="card" style="width: 18rem;">
                <div class="card-body">
                    <h1>/blocks/{{blockId}}</h1>
                </div>
            </div>
        </div>
    {{/each}}
</div>
  1. In my view, I loop through the data. data is completely valid there. Problem I have is in <h1>, blockId doesn't print anything. The reason that's causing this is the loop of #each data. As soon as I remove the loop, blockId is correct after that. What I want is that blockId should be the same for all elements of data.

  2. How can I grab the parameter from url in handlebars file to pass a href element? In this case, I would not need to return blockId again from express.

romellem
  • 5,792
  • 1
  • 32
  • 64
Nika Kurashvili
  • 6,006
  • 8
  • 57
  • 123
  • 1
    You would need to step up a context level when in the loop. As in `{{../blockId}}` or `{{@root.blockId}}`. See: https://handlebarsjs.com/guide/expressions.html#path-expressions – 76484 Nov 06 '20 at 14:22
  • 1
    Thank you . That worked out well. – Nika Kurashvili Nov 06 '20 at 23:58
  • Does this answer your question? [Access a variable outside the scope of a Handlebars.js each loop](https://stackoverflow.com/questions/13645084/access-a-variable-outside-the-scope-of-a-handlebars-js-each-loop) – 76484 Nov 11 '20 at 16:19

1 Answers1

1

Some helpers like #with and #each change the context of the data, so you need to include ../ to move up into parent contexts. See https://handlebarsjs.com/guide/expressions.html#changing-the-context

For your example, this looks like

<div class="row">
    {{#each data}}
        <div class="col">
            <div class="card" style="width: 18rem;">
                <div class="card-body">
                    <h1>/blocks/{{../blockId}}</h1>
                </div>
            </div>
        </div>
    {{/each}}
</div>

For the 2nd part, handlebars can't read from other window variables (like location), so passing this down as blockId in your route is the correct way to expose this information.

romellem
  • 5,792
  • 1
  • 32
  • 64