Nested if inside each (Handlebars template in Express app)

This morning I thought I'd finally look at Handlebars by putting together a quick Express app. I enjoy it so far (and I think I prefer Handlebars over 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 view and display posts with:

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

      

It's simple and works as expected, but I was then interested in adding something like an "Edit" button at the bottom of each post. I would like to set the visibility of this based on the user. If you're 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 figure out what if the user validates the work inside each one above. Is this possible in Handlebars? In Jade, in the past, I just used something like:

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

      

For clarity, the 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 am really new to Handlebars, so I hope this is really obvious. Thanks in advance and I hope you all have a great NYE!

+3


source to share


1 answer


  • You do not need to surround the each

    work if

    , each...else

    .
  • If you try to access user

    in each

    , you will actually try to access posts.user

    . You can access the parent context using ../

    .

eg.



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

      

+9


source







All Articles