How to evaluate parameter inside Freemarker macro?

。_饼干妹妹 提交于 2019-12-07 03:30:51

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/8367489/how-to-evaluate-parameter-inside-freemarker-macro

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!