Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set null to a variable in freemarker

Tags:

freemarker

I can't find anything related to this on any question, and it is something really basic, but I can't figure it out.

So my problem is that I don't know how to set null to a variable in freemarker. Example:

${hi!"bye"}          <#-- Prints "bye" because hi is undefined -->
<#assign hi="hi">    <#-- Sets a value to the var hi -->
${hi!"bye"}          <#-- Prints "hi" because hi has a value -->
<#assign hi=null>    <#-- This does not work but is what I am looking for -->
${hi!"bye"}          <#-- I want it to print "bye" because hi should be undefined -->

I have this problem because I iterate over a list and set a var if some logic to the specific item validates, and then check if the var exists, but if the first item creates the var, then I will have the var set for the rest of the items in the list.

like image 631
Pablo Matias Gomez Avatar asked Aug 07 '14 19:08

Pablo Matias Gomez


2 Answers

Depending on what you need it for, you can use a different type to indicate a "missing" value.

For instance, if you have myVariable that is normally a number, assign false to it, and then instead of checking myVariable??, check myVariable!false?is_number. This will cover both cases (non-existent and "unset").

${ (myVariable!false?is_number)?c }

<#assign myVariable = 12 >
${ (myVariable!false?is_number)?c }

<#assign myVariable = false >
${ (myVariable!false?is_number)?c }

Result:

false
12
false

Go try.

like image 43
Ondra Žižka Avatar answered Oct 22 '22 10:10

Ondra Žižka


You could assign an empty string to your variable and check with the buit-in ?has_content if it is set:

${hi?has_content?then(hi, "bye")}
<#assign hi="hi">
${hi?has_content?then(hi, "bye")}
<#assign hi="">
${hi?has_content?then(hi, "bye")}

This will render:

bye
hi
bye
like image 196
Jasper de Vries Avatar answered Oct 22 '22 11:10

Jasper de Vries