Re: FreeMarker convert non-scalar to scalar
Erin Drummond <[email protected]>
| Newsgroups | gmane.comp.web.freemarker.user |
|---|---|
| Message-ID | <[email protected]> |
It appears to be possible using a Macro:
<#macro to_s object>
<@compress single_line=true>
<#if object?is_hash || object?is_hash_ex>
<#assign first="true">
{
<#list object?keys as key>
<#if first="false">,</#if>
<#assign value><@to_s object=object[key] /></#assign>
"${key}" : ${value?trim}
<#assign first="false">
</#list>
}
<#elseif object?is_enumerable>
<#assign first="true">
[
<#list object as item>
<#if first="false">,</#if>
<#assign value><@to_s object=item /></#assign>
${value?trim}
<#assign first="false">
</#list>
]
<#else>
"${object?trim}"
</#if>
</@compress>
</#macro>
However, this solution is verbose to call and not very elegant, is
there a better way?
On Tue, Aug 31, 2010 at 3:36 PM, Erin Drummond <[email protected]> wrote:
> Hello,
>
> I have frequently found the need to convert Hash and Sequence objects
> to Scalars in my FreeMarker templates (for debugging purposes mainly,
> so I can see what data is being made available in the template). The
> scalar representation would be identical to how you define them, for
> example a Hash would convert to "{ "key" : "value" }" and a Sequence
> would convert to "[ "item1", "item2" ]". However, I have not been able
> to find such functionality in FreeMarker. I tried to create a custom
> Method to do it, but it just errors out saying that it expects a
> Scalar as a parameter only.
>
> How would I go about achieving this in FreeMarker? Would I have to try
> and create a "to_s" builtin (if so, where do I start?), or is there a
> way to create methods that can accept non-scalar arguments?
>
> Thanks,
> Erin
>
------------------------------------------------------------------------------
This SF.net Dev2Dev email is sponsored by:
Show off your parallel programming skills.
Enter the Intel(R) Threading Challenge 2010.
http://p.sf.net/sfu/intel-thread-sfd