【问题标题】:Freemarker - print an object into another objectFreemarker - 将一个对象打印到另一个对象中
【发布时间】:2021-11-04 09:40:13
【问题描述】:

我目前正在使用 FreeMarker Java 模板引擎 (.ftl)

我有一个配置文件对象,我想打印到另一个 ftl 文件 (OutputScript.ftl)

这是我的 config.ftl

<#assign config = {
"hp": {
    "product" : {
        "title": {
            "top": "true",
            "bottom": "false"
        }
    }
}
} />

这是我的 OutputScript.ftl

<script>
window.object = {
    config : {
        // write the config object inside
    }
}
</script>

我已经建立了一个页面 (page.ftl) 我调用这两个文件

<#import "/config/config.ftl" as config />
<#attempt><#include "XXX/OutputScript.ftl" /><#recover><!--Error: module OutputScript.ftl ${.error}--></#attempt>

目前,我无法将其打印出来。 我试过这样的东西没有任何运气

          <#if config.config.hp??>
            <#list config.config.hp as page>
                ${key}: ${page[key]}
            </#list>
        </#if>

另外,我们可以让它动态吗?(如果我的配置文件会有更多的缩进,它还能工作吗?)

谢谢

【问题讨论】:

  • 请始终在您的问题中包含错误消息。

标签: java freemarker


【解决方案1】:

您不能直接使用${} 打印地图(“哈希”),只能使用字符串、数字、日期/时间或布尔值。所以如果要生成JSON,就得编写宏,递归地遍历和打印数据结构。

【讨论】:

  • 你有链接作为例子吗?我需要一些可以遍历所有第一个对象的东西+检测该站点是否是一个对象或显示它。 if 对象再次循环等
【解决方案2】:

我已将 Freemarker 更新到最新版本,以便使用 ?eval_json

<#assign config = '{
    "test" :"testValue",
    "hp": {
        "product" : {
            "title": {
                "top": {
                    "header": {
                        "big": "true",
                        "test" : 14
                    },
                    "header2": {
                        "big2": "true2"
                    },
                    "header3" : "true3"
                }
            }
        }
    }
}'>

<#assign configRedux = config?eval_json>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-10
    • 1970-01-01
    相关资源
    最近更新 更多