【发布时间】:2013-10-02 10:15:27
【问题描述】:
我想查看 freemarker 数据模型中的所有变量,就像 struts2 debug 标记显示值堆栈。
freemarker 有没有办法做到这一点?
【问题讨论】:
标签: freemarker
我想查看 freemarker 数据模型中的所有变量,就像 struts2 debug 标记显示值堆栈。
freemarker 有没有办法做到这一点?
【问题讨论】:
标签: freemarker
对此没有通用的解决方案,但您可以尝试
<#list .data_model?keys as key>
${key}
</#list>
如果数据模型只是普通的 Map 或 JavaBean,则此方法有效,但对于更复杂的数据模型,如果它支持 ?keys 并且它确实返回所有内容,则取决于数据模型实现。
您还拥有您在模板中设置的变量,可以像上面一样列出,只是使用.globals、.namespace(表示当前模板命名空间)和.locals,而不是.data_model。
您可能还拥有Configuration 级别的共享变量,并且无法从 FTL 中列出这些变量(您可以为它编写一个自定义的 TemplateMethodModel 来读取 Configuration.getSharedVariableNames(),然后从模板中调用它) .
当然,理想情况下,FreeMarker 应该有一个 <#show_variables> 指令或其他东西,尽最大努力展示这一切......但遗憾的是还没有这样的东西。
【讨论】:
Expected an extended hash, but this evaluated to a hash 错误。这是否意味着 .data_model 哈希不支持 ?keys 哈希运算符?
更详细的方法是这个宏:
<#macro dump_object object debug=false>
<#compress>
<#if object??>
<#attempt>
<#if object?is_node>
<#if object?node_type == "text">${object?html}
<#else><${object?node_name}<#if object?node_type=="element" && object.@@?has_content><#list object.@@ as attr>
${attr?node_name}="${attr?html}"</#list></#if>>
<#if object?children?has_content><#list object?children as item>
<@dump_object object=item/></#list><#else>${object}</#if> </${object?node_name}></#if>
<#elseif object?is_method>
#method
<#elseif object?is_sequence>
[<#list object as item><@dump_object object=item/><#if !item?is_last>, </#if></#list>]
<#elseif object?is_hash_ex>
{<#list object as key, item>${key?html}=<@dump_object object=item/><#if !item?is_last>, </#if></#list>}
<#else>
"${object?string?html}"
</#if>
<#recover>
<#if !debug><!-- </#if>LOG: Could not parse object <#if debug><pre>${.error}</pre><#else>--></#if>
</#attempt>
<#else>
null
</#if>
</#compress>
</#macro>
<@dump_object object=.data_model/>
这为您提供了数据模型的完整转储。
【讨论】:
这是修改为发出 JSON 的 @lemhannes 宏定义。在一个相当简单的数据模型上进行了轻微测试
<#macro dump_object object debug=false>
<#compress>
<#if object??>
<#attempt>
<#if object?is_node>
<#if object?node_type == "text">${object?json_string}
<#else>${object?node_name}<#if object?node_type=="element" && object.@@?has_content><#list object.@@ as attr>
"${attr?node_name}":"${attr?json_string}"</#list></#if>
<#if object?children?has_content><#list object?children as item>
<@dump_object object=item/></#list><#else>${object}</#if>"${object?node_name}"</#if>
<#elseif object?is_method>
"#method"
<#elseif object?is_sequence>
[<#list object as item><@dump_object object=item/><#if !item?is_last>, </#if></#list>]
<#elseif object?is_hash_ex>
{<#list object as key, item>"${key?json_string}":<@dump_object object=item/><#if !item?is_last>, </#if></#list>}
<#else>
"${object?string?json_string}"
</#if>
<#recover>
<#if !debug>"<!-- </#if>LOG: Could not parse object <#if debug><pre>${.error}</pre><#else>-->"</#if>
</#attempt>
<#else>
null
</#if>
</#compress>
</#macro>
【讨论】: