How can I check null and empty both in freemarker string? - freemarker

For example.
String s can have these values like "value", "" or null.
<#if str?? && str?has_content>
${str}
</#if>
Can I check ??(null) and ?has_content(empty not null) both value in freemarker if statement not using TemplateModel?

str?has_content returns true if str is non-null (non-missing), and is also not a 0-length string. So you just need <#if str?has_content>.
(As of TemplateModel-s, every value is a TemplateModel as far as templates see. There's no such thing as a non-TemplateModel value.)

Related

FreeMarker if statement comparing two values

I'm trying to compare two values
<#if user.cellPhone != changedUser.cellPhon>
<br><span class="changes">*${changedUser.cellPhone}</span></#if>
I'm getting an error
freemarker.core.InvalidReferenceException: The following has evaluated to null or missing:==> changeUser
Tip:
If the failing expression is known to legally refer to something that's sometimes null or missing, either specify a default value like myOptionalVar!myDefault, or use <#if myOptionalVar??>when-present<#else>when-missing. (These only cover the last step of the expression; to cover the whole expression, use parenthesis: (myOptionalVar.foo)!myDefault, (myOptionalVar.foo)??
Add null check to condition changedUser??:
<#if changedUser?? && user.cellPhone != changedUser.cellPhon>

String replace in FTL with a specific word

I need to replace a specific string in a URL in FTL.
Code 1:
<#assign pageUrlWithParams= "https://sample.com/category?filter=low&navParam=Appliances&skrLocale=en_US&t=1"/>
<#if pageUrlWithParams?? && pageUrlWithParams != '' && pageUrlWithParams?contains("skrLocale")>
<#assign pageUrlWithParams = pageUrlWithParams?replace('skrLocale','')/>
</#if>
${pageUrlWithParams}
Code 2 :
<#assign pageUrlWithParams= "https://sample.com/category?filter=low&navParam=Appliances&skrLocale=en_FR&t=2"/>
<#if pageUrlWithParams?? && pageUrlWithParams != '' && pageUrlWithParams?contains("skrLocale")>
<#assign pageUrlWithParams = pageUrlWithParams?replace('skrLocale','')/>
</#if>
${pageUrlWithParams}
I need to remove "skrLocale=en_US" and "skrLocale=en_FR" from pageUrlWithParams.
Known text is "skrLocale", using this I need to remove "skrLocale=en_US" and "skrLocale=en_FR".
Because of en_US and en_FR, i dont know how to take that that part after equals.
Some suggest an answer please. Thanks in advance
Using regular expressions ('r' as 3rd parameter to ?replace) is the key. Note that due to the complexity of URL syntax, we need to handle two edge cases (skrLocale is the first parameter, and skrLocale is the only parameter), which the below function fulfills. However, it doesn't handle %xx escapes in the parameter name (which you might don't care about):
<#function removeSkrLocale url>
<#return url?replace(r'([&\?])skrLocale=[^&]*&?', '$1', 'r')?remove_ending('?')>
</#function>
${removeSkrLocale(pageUrlWithParams)}
Of course you can do this without #function as well, directly inside the ${}, but it's reusable and more self documenting this way.
I would use a Freemarker function (this is a simple version, can be improved)
<#function remove_param_if_value_equals pageUrlWithParams paramName, paramValues >
<#if pageUrlWithParams?has_content && pageUrlWithParams?contains(paramName)>
<#list paramValues as paramValue>
<#local paramNameAndValue = paramName + "=" + paramValue />
<#local pageUrlWithParams = pageUrlWithParams?replace(paramNameAndValue,'')/>
</#list>
</#if>
<#return pageUrlWithParams />
</#function>
<#assign pageUrlWithParams= "https://sample.com/category?filter=low&navParam=Appliances&skrLocale=en_US&t=1"/>
<#assign pageUrlWithParams = remove_param_if_value_equals(pageUrlWithParams, "skrLocale", ["en_US", "en_FR"]) />
${pageUrlWithParams}
The code that does the business remains isolated and can be altered/improved later on.
(For example there is that double "&" that could be cleaned)
I don't know about FTL. But if you need to replace parameter skrLocale in your URL, I think below is good pattern you can use:
(skrLocale(.*?)&)
With (.*?) is called lazy, it match from skrLocale to nearest &. Therefore, with your case, it will match skrLocale=en_US& and skrLocale=en_FR& .

Freemarker assign value to variable

I'm having trouble while trying to assign value to a variable using Freemarker.
<#if size??>
<#assign num=size?number>
<#if (num>0)>
<#list 0..num-1 as i>
<#if .vars['abc'+i?c] = "test">
<#assign .vars['abc'+i?c] = .vars['abc'+i?c]?replace("test","Test")>
</#if>
</#list>
</#if>
This is the error message: Encountered ".", but was expecting one of:
STRING_LITERAL
RAW_STRING
ID
Can anyone help me with this?
Thank you.
You can only write top-level variables in a FreeMarker template. Also you can't assign to a variable with dynamically constructed name, except with an ?interpret hack: <#"<#assign abc${i?c} = abc${i?c}?reaplce('test', "Test")>"?interpret />. Obviously that's horrid... BTW, what's the use case here? Why do you need to assign to dynamically constructed variable names?

Freemarker check if variable exists and is different than zero

${something.id!} can help me check the variable exists. But what if I also want to check if it is not 0?
[#if something.id?? && something.id!=0]
${something.id}
[/#if]
Or with the standard freemarker syntax:
<#if something.id?? && something.id!=0>
${something.id}
</#if>
You could use an if statement such as
<#assign id0=0>
<#assign id1=1>
id0=<#if id0?? && id0 != 0>${id0}</#if>,
id1=<#if id1?? && id1 != 0>${id1}</#if>,
idx=<#if idx?? && idx != 0>${idx}</#if>
Output
id0=, id1=1, idx=
Or better yet use a function. This function uses a default of zero for the value so that it can handle missing/null values. It will return a zero length string if the value is zero or null otherwise the original value.
<#function existsNotZero value=0>
<#if value == 0>
<#return "">
<#else>
<#return value>
</#if>
</#function>
<#assign id0=0>
<#assign id1=1>
id0=${existsNotZero(id0)},
id1=${existsNotZero(id1)},
idx=${existsNotZero(idx)}
Output
id0=, id1=1, idx=
Like this:
<#if (something.id!0) != 0>${something.id}</#if>

Handling null values in Freemarker

How to handle null values in Freemarker? I get some exceptions in the template when null values are present in data.
Starting from freemarker 2.3.7, you can use this syntax :
${(object.attribute)!}
or, if you want display a default text when the attribute is null :
${(object.attribute)!"default text"}
You can use the ?? test operator:
This checks if the attribute of the object is not null:
<#if object.attribute??></#if>
This checks if object or attribute is not null:
<#if (object.attribute)??></#if>
Source: FreeMarker Manual
I think it works the other way
<#if object.attribute??>
Do whatever you want....
</#if>
If object.attribute is NOT NULL, then the content will be printed.
Use ?? operator at the end of your <#if> statement.
This example demonstrates how to handle null values for two lists in a Freemaker template.
List of cars:
<#if cars??>
<#list cars as car>${car.owner};</#list>
</#if>
List of motocycles:
<#if motocycles??>
<#list motocycles as motocycle>${motocycle.owner};</#list>
</#if>
I would like to add more context if you have issues and this is what I have tried.
<#if Recipient.account_type?has_content>
… (executes if variable exists)
<#else>
… (executes if variable does not exist)
</#if>
This is more like Javascript IF and ELSE concept where we want to check whether this value or another chaining through required logic.
Freemarker webite
Other reference:
Scenario: Customer has ID and name combined like 13242 Harish, so where our stakeholder need the only name, so I have tried this ${record.entity?keep_after(" ")} and it did work, however, it can only work when you have space, but when a customer doesn't have space and one name, I had to do some IF ELSE condition to check Null value.
Use:
${(user.isSuperman!false)?c}
It will work when "isSuperman" is null and when have boolean value
What we want:
For "null" we want to output 'false'
For boolean value and want to output value ('true' or 'false')
What we know:
boolean need to convert to string by using "?c" see Built-ins for booleans
but null we cannot convert to string and we need to use "!" see Handling missing values

Resources