Question

I want to show a number sequence in black color, and show nested sequence number in red. Here is my marco code:

<#macro test datas isNested>
    <#list datas as d>
    <#if d?is_enumerable>
        <#local isNested = true>
        <#if isNested>
            <#-- become red if it is nested -->
            Hi, I am going to be red!
                            <#-- some business code -->
        </#if>
        <@test d isNested/>
    <#else>
        <#if isNested>
            <span style="color:red;">${d}</span>
        <#else>
            ${d}
        </#if>
    </#if>
</#list>
</#macro>

call it like this:

<@test [1,2,3,[4,5],6,7] false/>
I want it to be:
1 2 3 Hi, I am going to be red! 4 5 6 7
only 4 and 5 show in red.
But now I get this:

1 2 3 Hi, I am going to be red! 4 5 6 7

all of 4 5 6 7 are show in red.

I think this line of code <#local isNested = true> play the trick. I also try to use assign, global, all of 1 2 3 4 5 6 7 are black.

so how should I do? Thx in advance.

PS:
I don't know how to make code show in red in stackoverflow, if any one knows plz helps me to edit my code.

Was it helpful?

Solution

Your problem is not FreeMarker-specific. You flip the isNested local variable (which also holds the parameter value) to true before the recursive @test call, and you leave if so after the recursive macro call has returned. So when the iteration of 6 and 7 comes, isNested is already true. You should not set the isNested at all, just pass true to the recursive call. Here:

<#macro test datas isNested=false>
    <#list datas as d>
        <#if d?is_enumerable>
            Hi, I am going to be red!
            <@test d true />
        <#else>
            <#if isNested>
                <span style="color:red;">${d}</span>
            <#else>
                ${d}
            </#if>
        </#if>
    </#list>
</#macro>

<@test [1,2,3,[4,5],6,7] />
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top