Search code examples
htmlnode.jsexpress-handlebars

how to build a dynamic a href link with data given in object (Node.js && handlebars)


After an hour or so of searching, I didn't find any help so I'm asking here (my question is in second code block on lines 5 & 6). I have an array of objects sent from server to client like so:

router.get('/tasks', ensureAuthenticated, function(req, res, next) {
    db.tasks.find({ forUser: req.params.userId }, function (err, tasks) {
        res.render('tasks', { tasks: tasks }); // EACH TASK(obj) FROM TASKS(arr) HAS ITS _id
    });
});

And I'm showing those tasks on the client via handlebars like so: tasks.handlebars

<ul class="list-group">
{{#if tasks}}
    {{#each tasks}}
        <div class="list-group">
            <!-- This is where I got lost, here in this href should be /task/:id -->
            <a href='WHAT GOES HERE?' class="list-group-item list-group-item-action flex-column align-items-start">
                <div class="d-flex w-100 justify-content-between">
                    <h5 class="mb-1">{{title}}</h5>
                    <div class="row" style="padding-left: 25px">
                        <small>From: {{dateCreated}}</small>
                        <small>To: {{deadline}}</small>
                    </div>
                </div>
                <p class="mb-1">{{description}}</p>
            </a>
        </div>
    {{/each}}
{{else}}
    <p>No tasks.</p>
{{/if}}

So on each task should go an onclick function that calls this on server:

router.get('/task/:id', ensureAuthenticated, function(req, res, next) {
    db.tasks.findOne({_id: mongojs.ObjectId(req.params.id) }, function (err, task) {
        if (err) res.send(err);
        res.json(task);
    }); 
});

Solution

  • According to the handlebars docs, you don't need the if block, an each block can be followed by an else at the same level. At first glance, you want href="{{this._id}}".