Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested if inside each (Handlebars template in Express app)

This morning I figured I'd finally take a look at Handlebars by throwing together a quick Express app. I'm enjoying it so far (and I think I prefer Handlebars to Jade) but I have a problem. The app I'm playing with is (yet another) basic CMS using Mongo. On the /posts/index page, I'm checking for and displaying posts with:

{{#if posts}}
  {{#each posts}}
    <h4>{{title}}
    <p>{{content}}</p>
  {{/each}}
{{else}}
  <p>There are no posts.</p>
{{/if}}

This is simple and works as expected but I was then wondering about adding something like an Edit button at the bottom of each post. I'd like to condition the visibility of this based on user. If logged in (I'm using Passport's local strategy), I can easily see the user's details with:

{{#if user}}
  {{user.name}}
{{/if}}

The problem, however, is that I can't seem to get that if user check working inside the each above. Is this possible in Handlebars? In Jade, in the past, I've just used something like:

if(posts.length)
  each post in posts
    #{post.title}
    if(user)
      ...

For the sake of clarity, the get route for the posts page is:

router.get('/', function(req, res) {
  Post.find({}, function(err, posts) {
    res.render('posts/index', {
      title: 'Posts',
      user: req.user,
      posts: posts,
    });
  });
});

As mentioned, I'm really new to Handlebars so I'm hoping this is something really obvious. Thanks in advance and I hope you all have a great NYE!

like image 313
Darryl Young Avatar asked Dec 31 '14 09:12

Darryl Young


Video Answer


1 Answers

  • You don't need to surround the each with an if, each...else works.
  • If you try to access user within the each, you'll actually be trying to access posts.user. You can access the parent context using ../.

E.g.

{{#each posts}}
  <h4>{{title}}
  <p>{{content}}</p>
  {{#if ../user}}
    {{../user.name}}
  {{/if}}
{{else}}
  <p>There are no posts.</p>
{{/each}}
like image 107
Matt Cain Avatar answered Oct 13 '22 01:10

Matt Cain