14

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?

Ryan Payne
  • 5,249
  • 4
  • 28
  • 69
  • Does this answer your question? [Handling null values in Freemarker](https://stackoverflow.com/questions/13950289/handling-null-values-in-freemarker) – Jasper de Vries Jan 17 '20 at 06:24
  • Does this answer your question? [Exclamation mark behind assigned value: A = B ! C](https://stackoverflow.com/questions/35852357/exclamation-mark-behind-assigned-value-a-b-c) – Jan Jan 17 '20 at 12:01
  • @JasperdeVries That gets close but does not provide a direct answer nor a direct source to the definition of the "default value operator". – Ryan Payne Jan 17 '20 at 16:53
  • @Jan That is similar but references an interchange tagged with `javascript`. Will someone searching for a FreeMarker answer to this question find that interchange sufficient? – Ryan Payne Jan 17 '20 at 16:54

1 Answers1

21

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.

Ryan Payne
  • 5,249
  • 4
  • 28
  • 69
  • 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 https://freemarker.apache.org/docs/dgui_template_exp.html#dgui_template_exp_missing and https://freemarker.apache.org/docs/app_faq.html#faq_null for more information. – Jan Jan 17 '20 at 12:11
  • 1
    @Jan 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." https://freemarker.apache.org/docs/dgui_template_exp.html#dgui_template_exp_missing. I've used the default value operator many times without a default value and never seen any errors. Am I missing something? – Ryan Payne Jan 17 '20 at 16:50
  • 1
    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. – Jan Jan 20 '20 at 07:01
  • @Jan 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. – Ryan Payne Jan 20 '20 at 15:53