views:

4969

answers:

2

Hi,

I have a Freemarker template which contains a bunch of placeholders for which values are supplied when the template is processed. I want to conditionally include part of the template if the userName variable is supplied, something like:

[#if_exists userName]
  Hi ${userName}, How are you?
[/#if_exists]

However, the FreeMarker manual seems to indicate that if_exists is deprecated, but I can't find another way to achieve this. Of course, I could simple providing an additional boolean variable isUserName and use that like this:

[#if isUserName]
  Hi ${userName}, How are you?
[/#if]

But if there's a way of checking whether userName exists then I can avoid adding this extra variable.

Cheers, Don

+8  A: 
[#if userName??]
   Hi ${userName}, How are you?
[/#if]

Or with the standard freemarker syntax:

<#if userName??>
   Hi ${userName}, How are you?
</#if>
Ulf Lindback
beat me by a couple seconds. :)
Herms
In case anyone else was thrown off by this, the #if syntax should be surrounded by less than and greater than characters rather than brackets. for instance: <#if userName??>
Cameron
It is actually possible to use this syntax, so I just followed the syntax of the question:see http://freemarker.sourceforge.net/docs/dgui_misc_alternativesyntax.html
Ulf Lindback
+2  A: 

Also I think *if_exists* was used like:

Hi ${userName?if_exists}, How are you?

which will not break if userName is null, the result if null would be:

Hi , How are you?

if_exists is now deprecated and has been replaced with the default operator ! as in

Hi ${userName!}, How are you?

the default operator also supports a default value, such as:

Hi ${userName!"John Doe"}, How are you?
Ulf Lindback
freaky syntax...
skaffman