如何在 freemarker ( .ftl ) 中转储对象

问题描述 投票:0回答:2

有没有办法转储整个对象并将其写入某处?

喜欢:

var_dump()
在 PHP 中 JS 中的
console.log

我发现了类似

list
的东西,所以我尝试了下面这样的东西:

<#list calculation as c>
${c}
</#list>

但是模板出错了。我感谢任何建议!

freemarker
2个回答
10
投票

这取决于您要迭代的对象的类型。您可以检查变量的数据类型,然后将其输出适当的(参考:http://freemarker.incubator.apache.org/docs/ref_builtins_expert.html#ref_builtin_isType

以下是一些示例:

<#if calculation?is_sequence>
  <#list calculation as c>
    ${c}
  </#list>
<#elseif calculation?is_hash_ex>
  <#list calculation?keys as key>
    ${key} - ${calculation[key]}
  </#list>
<#elseif calculation?is_string>
  ${calculation}
</#if>

查看 https://github.com/ratherblue/freemarker-debugger/blob/master/debugger.ftl 了解更多有关转储数据的示例


0
投票
Assuming, message is the object in your code. You can follow these steps:
But first do the syntax interpolation of your object.
1) Put message in these curly braces {}, so it looks like: {message}
2) Prefix it with a $ sign, now it would look like: ${message}
3) Suppose x = ${message}
4) Put x between `` (backticks), so it looks like: ```` x ```. 
5) Finally, it would look like: `${message}` (only single backtick before $ and after closing curly brace)
6) Finally, put option1 or option2 inside a opening & closing script tag. Put this code at the end of your ftl file as objects might load on your frontend after a setTimeout.
7) Wherever you're seeing ${message} in the below options, put it inside a ``

Option1:

    <script>
      const values = Object.values(`${message}`);
      console.log("Values:", values);
    </script>

Option2:

    <script>
      const val = Object.values(`<#if message?is_string>${message}<#else>${message?json_string}</#if>`);
      console.log("Val:", val);
    </script>
© www.soinside.com 2019 - 2024. All rights reserved.