Search code examples
javahtmltemplatesfreemarker

How to concatene 2 strings in Freemarker template


I try to concatane 2 strings in my Freemarker template. The first one it's a constant and the second one come from the data model and I use the concatened string to get a label in the resource bundle. I try several combinaisons but they're worked

<@spring.messageText "resource.bundle.key" + ${dataModel.value}, "undefined"/>
<@spring.messageText ${"resource.bundle.key" + ${dataModel.value}}, "undefined"/>

thx


Solution

  • The '+' operator in FreeMarker is used to concatenate strings. Your syntax is a little strange, though. This is how to concatenate strings in FreeMarker the right way:

    <@spring.messageText "resource.bundle.key" + dataModel.value, "undefined"/>
    

    In this example, the value of ${dataModel.value} is concatenated with the constant string "resource.bundle.key". ${} around dataModel.value inside the string is not required.

    You can use brackets to ensure that there are no problems with the concatenation:

    <@spring.messageText ("resource.bundle.key" + dataModel.value), "undefined"/>
    

    This clearly states the order of operations.

    The spring.messageText macro receives the concatenated string that results in both scenarios. Verify that the key created by concatenating "resource.bundle.key" with the value of dataModel.value is present in your resource bundle.