【问题标题】:accessing nested fields in handlebars when rendering from vert.x从 vert.x 渲染时访问把手中的嵌套字段
【发布时间】:2026-01-22 18:50:01
【问题描述】:

我正在尝试使用具有命名字段的对象呈现页面:

{
    "context":{ 
          "greeting":"hello"
     }
}

我用一个非常简单的模板来渲染它:

    <html>
    <body>
        <div class="page">
            {{#with context}}
                <h1>{{greeting}} or {{this.greeting}}</h1>
            {{/with}}
                <h1>{{greeting}} or {{context.greeting}}</h1>
        </div>
    <div>the context is actually: {{context}} </div>
    </body>
    </html>

正如您在上面看到的,我目前正在尝试几种呈现greeting 值的方法。在此模板的早期版本中,我也一次尝试过所有这些。

在模板的最后,我渲染了整个context 变量,只是为了确保我传入的数据确实存在。这是结果的截图:

阅读了文档here 和教程here 我真的看不出我做错了什么,有人可以澄清一下吗?

我应该补充一点,我正在使用 io.vertx:vertx-web-templ-handlebars:3.3.3 来呈现这个

下面是返回此模板的 java 方法。我正在使用 Vert.x 渲染引擎。

private void handleStatus(RoutingContext ctx, TemplateEngine engine, String template)
{
    JsonObject json = new JsonObject();
    json.put("greeting", "hello");
    ctx.put("context", json);

    engine.render(ctx, template, res ->
    {
        if (res.succeeded())
        {
            ctx.response().end(res.result());
        }
        else
        {
            ctx.fail(res.cause());
        }
    });
}

这里是调用该方法的地方:

TemplateEngine engine = HandlebarsTemplateEngine.create();
statusHandler = new StatusHandler(vertx);
statusHandler.start();
deploymentHandler = new DeploymentHandler(vertx);

router.get("/monitor/apistatus").handler(ctx -> handleStatus(ctx, engine, "templates/apistatus.hbs"));

【问题讨论】:

  • 你的语法绝对没问题。检查使用 - tryhandlebarsjs.com。问题主要出在 Handlebars 初始化和编译代码上。理想情况下应该是 var source = document.getElementById("entry-template").innerHTML; var template = Handlebars.compile(source); var context = {sample Json data here}; var html = template(context); 在这里查看更多详细信息 - handlebarsjs.com。你能分享你的初始化代码吗?
  • 我使用 vert.x 渲染引擎,所以我害怕这并不是什么令人兴奋的事情。但是我已经编辑了我的问题以包含它
  • 我刚刚注意到您输出中的行 the context is actually: {"greeting":"hello"}。这意味着您将数据作为字符串而不是 JSON 对象传递。否则它只会打印the context is actually: [object Object]

标签: handlebars.js vert.x server-side-rendering html-rendering


【解决方案1】:

在 3.4.0 之前,Vert.x Web Handlebars 模板引擎did not work well with JsonObject and JsonArray

升级到 3.4/3.5,或者作为一种解决方法,您可以将 JsonObject 转换为 Map

【讨论】:

  • 这就是为什么!多谢!我最终将我的前端重写为一个 react-app 并从端点提供原始 json(幸运的是这是一个相当小的项目)。但现在我知道我是否想再次使用车把! :)