Search code examples
freemarker

How tu use a variable in if in ftl?


I am learning ftl and have problem with variables. I have an element a which has its own subelement b. I access the subelement with the following method:

a.getChild("b")

Now, I check whether a subelement has content in the following way:

<#if a.getChild("b").getData()?has_content>

and this works as expected.

Now, I wanted to shorten this if's syntax by doing the following:

<#assign b>${a.getChild("b")}</#assign>
<#if b.getData()?has_content>

However, this produces error:

For "." left-hand operand: Expected a hash, but this has evaluated to a string

What am I doing wrong and how do I eliminate the need for calling the getChild in ifs?

I have hundreds of ifs in my production environment which all use getChild, sometimes even multiple times if subelements are nested so it would be great if I could shorten the syntax by assigning a child element to a variable.

I just started learning ftl yesterday, so this might be stupid question, sorry.


Solution

  • Simply do <#assign b = a.getChild("b")>.

    With ${a.getChild("b")} you've outputted a string which then was assigned.

    See the documentation also: https://freemarker.apache.org/docs/ref_directive_assign.html