How to evaluate a parameter inside a Freemarker macro?

Suppose we have a simple Freemarker macro:

<#macro myMacro expr> <#local x=1> ${expr} </#local> <#local x=2> ${expr} </#local> </macro> 

<@myMacro "A" / "> gives:

and A


I need something like <@myMacro "A $ {x}" / "> should indicate:

A1 A2

but it doesn’t work like interpolating $ {x} until going into the macro. This does not work even if I use the raw string r "A $ {x}" as a parameter.

I tried to play with? eval, but no result yet (((

Can I do what I need?

+4
source share
1 answer

Do you want to evaluate the expression here or a fragment of the template? The expression is like 1 + 2 or "A${x}" (note the quotation marks, this is a string literal), which when passed will look like <@myMacro "1 + 2" /> and <@myMacro r'"A${x}"' /> ; the latter is quite inconvenient. The template snippet is similar to <#list 1..x as i>${i}</#list> or A${x} (note the absence of quotes), which is more powerful and looks better inside the line. From what I see, you probably want to evaluate the template fragment, so it should be:

 <#macro myMacro snippet> <#-- Pre-parse it for speed --> <#local snippet = snippet?interpret> <#local x = 1> <@snippet /> <#local x = 2> <@snippet /> </#macro> 

and then you can use it like:

 <@myMacro r"A${x}" /> 

or even:

 <@myMacro r"<ul><#list 1..x as i><li>${i}</li></#list><ul>" /> 

In any case, all of this is a bit weird using FreeMarker, and if you rely heavily on ?interpret or ?eval (for example, you make hundreds of them on an HTTP request), you might find it slow. Slow with Java standards, i.e.

+3
source

Source: https://habr.com/ru/post/1384468/


All Articles