javascriptnode.jsexpressexpress-handlebars

Accessing variables inside a handlebars #each loop


I'm dynamically trying to set a form's attributes and their values inside a handlebars template. I'm getting a falsy value for the below code because I'm executing the {{#if }} statement inside a {{#each }} loop and hence "this" is pointing to the array elements within the loop. Is there a way to access my "user" variable(not part of the array elements) inside the loop?

appointment.hbs file

{{#each this.classes}}
    <div class="divrow">
        <div class="container">

            <div id="imgdiv">                    
                
                <img class= "img-result" src="/images/{{this.photo}}" alt="Image1">  
                
            </div>    
            <div id="content-div">
                <h3>{{this.name}} and <em>{{this.email}}</em></h3>
                <p> {{this.age}} mins</p>

                {{#if user.loggedIn}}
                    <form action="/appointment/book" method="post">
                        <button type="submit" name="bookedClsId" value={{this._id}}>
                            Book Appointment
                        </button>
                    </form>
                {{else}}
                    <form action="/login" method="get">
                        <button type="submit" name="bookedClsId" value={{this._id}}>
                            Book Appointment
                        </button>
                    </form>
                {{/if}}
            </div>
        </div>
    </div>
{{/each}}

This is my res.render statement in the server.js file:

return res.render("classes", {layout: "layout",details: detailsFound , user: 
req.session.user});

Solution

  • You have to access parent context: {{#if ../user.loggedIn}}