Search code examples
freemarkertemplate-enginestring-concatenation

Concatenation strings in freemarker


How can I concatenate strings in freemarker?

This doesn't work.

    <#function foo input>
<#local str="Hello ">
${str} = ${str} + ${" world"}

<#return str>
</#function>

${foo("a")}

Here is online evaluator:
http://freemarker-online.kenshoo.com/

Edit: To make it clear I need to use it with variables, to be able write something like this.


public String sayHello() {return "Hello";}
public String sayWorld() {return "world"};
public String sayPeople() {return "people";}

public void main() { 
 String str = "";
 str += sayHello();
 str += "";
 str += sayWorld();
 str += "";
 str += sayPeople();

 return str;
}

Solution

  • Like <#return "Hello " + input + "!">, or <#return "Hello ${input}!">. If you try to print to the output inside a #function (as opposed to inside a #macro), it will be ignored.

    Edit: Analogously with the Java example added:

    <#function concatDemo>
     <#local str = "">
     <#local str += sayHello()>
     <#local str += " ">
     <#local str += sayWorld()>
     <#local str += "!">
     <#return str>
    </#function>
    
    <#function sayHello><#return "Hello"></#function>
    <#function sayWorld><#return "World"></#function>
    
    ${concatDemo()}