wilddev
wilddev

Reputation: 1954

How to evaluate parameter inside 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:

A A


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

A1 A2

but it doesn't work as ${x} interpolated before passing into macro. This doesn't work even if I use raw string r"A${x}" as a parameter.

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

Is it possible to do what I need?

Upvotes: 6

Views: 4220

Answers (1)

ddekany
ddekany

Reputation: 31112

Do you want to evaluate an expression here, or a template snippet? An expression is like 1 + 2 or "A${x}" (note the quotation marks; it's a string literal), which when you pass it in will look like <@myMacro "1 + 2" /> and <@myMacro r'"A${x}"' />; the last is quite awkward. A template snippet is like <#list 1..x as i>${i}</#list> or A${x} (note the lack of quotation marks), which is more powerful and looks nicer inside a string. From what I'm seeing, you probably want to evaluate a template snippet, 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 as:

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

or even:

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

Anyway, the whole thing is a bit strange usage of FreeMarker, and if you rely very heavily on ?interpret or ?eval (like you do hundreds of it per HTTP request), you will possibly find it slow. Slow with Java standards, that is.

Upvotes: 5

Related Questions