Search code examples
freemarker

Freemarker assigning escaped ${expression} to a variable


I need to assign an escaped ${expression} to a variable in Freemarker

From the question here, it's clear that we can escape the $ sign in this way

${r"${expression}"}

This works perfectly outside Freemarker context, but doesnot working inside. I am trying to do

<#assign x = "${r"${expression}"}">

But getting the following error:

Template inclusion failed: You can't use "${" here as you are already in FreeMarker-expression-mode. Thus, instead of ${myExpression}, just write myExpression. (${...} is only needed where otherwise static text is expected, i.e, outside FreeMarker tags and ${...}-s.)

What is the way to achieve this? Thanks in advance.


Solution

  • I had to spent some time to figure out the following scenarios to escape ${expression} -

    • In Freemarker assignment:

    <#assign var = r"${expression}">

    • In html attribute:

    <a href="/user/${r"${expression}"}"> Some link </a>

    • In Freemarker concatenation:

    <#assign x = "something&"+r"${expression}"/>