将整个 Freemarker 数据模型暴露给 JavaScript?

发布于 2024-12-20 05:25:52 字数 214 浏览 1 评论 0 原文

我想知道是否有一种简单的方法可以将 Freemarker 模板的整个数据模型公开给 JavaScript,最好是在途中将其转换为 JS 对象文字。

我知道如何迭代键:

  <#list .data_model?keys as key>
  </#list>

并且大概我可以在模板中构建一个全局 JS 变量?

I'm wondering is there an easy way to expose the entire data model of a Freemarker template to JavaScript, preferably converting it to a JS object literal somewhere along the way.

I know how to iterate through the keys:

  <#list .data_model?keys as key>
  </#list>

And presumably I could build a global JS variable within the template as such?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦忆晨望 2024-12-27 05:25:52

您可以使用 FreeMarker 遍历整个数据模型,然后为相应的 JSON 对象生成“源代码”,但您必须处理诸如字符串转义之类的问题(例如,使用 js_string 内置)和潜在的大型(递归)对象图。

几年前,我编写了一个通用数据模型“dumper”,它打印 FreeMarker 数据模型的漂亮树表示。这可能不完全是您想要或需要的,但也许它是一种灵感。您可以在此处找到它。

You could traverse the whole data model with FreeMarker and then produce the "source code" for a corresponding JSON object, but you'd have to deal with things like string escaping (e.g. with the js_string builtin) and potentially large (recursive) object graphs.

Some years ago I wrote a generic data model "dumper" which prints a nice tree representation of the FreeMarker data model. It's probably not exactly what you want or need, but maybe it's an inspiration. You can find it here.

挖鼻大婶 2024-12-27 05:25:52

您还可以使用 Jackson 或任何其他 json api 将对象转换为 json,然后将 json 字符串添加到模型中。

使用 spring MVC 的示例:

@RequestMapping(value = "/test", method = RequestMethod.GET)
public ModelAndView test() throws Exception {


    String output = new ObjectMapper().writer().withDefaultPrettyPrinter().writeValueAsString(new HashMap<String, Object>());

    Map<String, Object> model = new HashMap<>();
    model.put("result", output);
    return new ModelAndView("page", "model", model);
}

在 freemarker

${model.result}中

You could also just use Jackson or any other json api to convert the object to json and then add the json string to the model.

Example using spring MVC:

@RequestMapping(value = "/test", method = RequestMethod.GET)
public ModelAndView test() throws Exception {


    String output = new ObjectMapper().writer().withDefaultPrettyPrinter().writeValueAsString(new HashMap<String, Object>());

    Map<String, Object> model = new HashMap<>();
    model.put("result", output);
    return new ModelAndView("page", "model", model);
}

In freemarker

${model.result}

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文