将整个 Freemarker 数据模型暴露给 JavaScript?
我想知道是否有一种简单的方法可以将 Freemarker 模板的整个数据模型公开给 JavaScript,最好是在途中将其转换为 JS 对象文字。
我知道如何迭代键:
<#list .data_model?keys as key>
</#list>
并且大概我可以在模板中构建一个全局 JS 变量?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 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.
您还可以使用 Jackson 或任何其他 json api 将对象转换为 json,然后将 json 字符串添加到模型中。
使用 spring MVC 的示例:
在 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:
In freemarker
${model.result}