You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Handlebars的#each循环内访问外部user变量?

问题:Handlebars循环内访问外部user变量

在Handlebars模板的{{#each}}循环中,由于this指向当前数组元素,无法直接访问外部传入的user变量,导致{{#if user.loggedIn}}判断始终返回假值,如何在循环内正确访问外部的user变量?

模板代码(appointment.hbs)

{{#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}}

后端渲染代码(server.js)

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

解决方案

Handlebars提供了@root特殊变量,用于访问模板的根级上下文(即通过res.render传入的最外层数据对象)。只需将循环内的user.loggedIn改为@root.user.loggedIn即可:

修改后的模板代码

{{#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 @root.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}}

后端的res.render代码无需修改,保持原样即可。


内容的提问来源于stack exchange,提问作者Amey079

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 04:55:31