What does the ! (exclamation point) in FreeMarker do?
Asked Answered
T

1

15

I keep seeing exclamation points at the end of FreeMarker code in Magnolia code examples. For example:

${content.header!}

What is the exclamation point called and what does it do?

Tribunate answered 17/1, 2020 at 3:29 Comment(4)
Does this answer your question? Handling null values in FreemarkerRamonaramonda
Does this answer your question? Exclamation mark behind assigned value: A = B ! CMackenzie
@JasperdeVries That gets close but does not provide a direct answer nor a direct source to the definition of the "default value operator".Tribunate
@Mackenzie That is similar but references an interchange tagged with javascript. Will someone searching for a FreeMarker answer to this question find that interchange sufficient?Tribunate
T
22

The exclamation point is called a default value operator. It's used to set a default value when an interpolation (${...}) returns null. If no default value is set, it returns an empty string ("").

${content.header!}
<#-- Returns "" if content.header is null -->

${content.header!"Example Header"}
<#-- Returns "Example Header" if content.header is null -->

See Dealing with missing variables for more info.

Tribunate answered 17/1, 2020 at 3:29 Comment(4)
Wrong. If the variable is null and you try to print it w/o providing default value via exclamation syntax, freemarker will print an error. See freemarker.apache.org/docs/… and freemarker.apache.org/docs/app_faq.html#faq_null for more information.Mackenzie
@Mackenzie I'm seeming this on the FreeMarker docs: "If the default value is omitted, then it will be empty string and empty sequence and empty hash at the same time." freemarker.apache.org/docs/…. I've used the default value operator many times without a default value and never seen any errors. Am I missing something?Tribunate
I guess I was too quick in reading the statement above. What i read was "if no value [of the property] is set it will return empty string", which is wrong. But what you were referring to was the "default value" after the exclamation which indeed can be omitted and is defaulted to empty string. My apologies.Mackenzie
@Mackenzie No apology needed. We all jump to conclusions at one time or another. I've enjoyed interacting with you here on Stack Overflow and I look forward to future interchanges.Tribunate

© 2022 - 2024 — McMap. All rights reserved.