如何评估Freemarker宏中的参数? [英] How to evaluate parameter inside Freemarker macro?

查看:106
本文介绍了如何评估Freemarker宏中的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个简单的Freemarker宏:

Suppose we have a simple Freemarker macro:

<#macro myMacro expr>

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

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

</macro>


< @myMacro"A"/>给出:


<@myMacro "A"/> gives:

A A

我需要类似的东西 < @myMacro"A $ {x}"/>应提供:

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

A1 A2

,但是在传递给宏之前,它不能作为$ {x}进行内插处理. 即使我使用原始字符串r"A $ {x}"作为参数,这也不起作用.

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.

我试图玩?eval,但没有结果((((

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

有可能做我需要做的事吗?

Is it possible to do what I need?

推荐答案

您要在此处计算表达式还是模板片段?表达式类似于1 + 2"A${x}"(请注意引号;它是字符串文字),当您将其传递时,其外观将类似于<@myMacro "1 + 2" /><@myMacro r'"A${x}"' />;最后一点很尴尬.模板代码段类似于<#list 1..x as i>${i}</#list>A${x}(请注意没有引号),它更强大,并且在字符串中看起来更好.根据我所看到的,您可能想要评估一个模板代码段,因此应该是:

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>

然后您可以将其用作:

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

甚至:

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

无论如何,整个事情都是FreeMarker的一种奇怪用法,如果您非常依赖?interpret?eval(就像您对每个HTTP请求进行数百次操作一样),则可能会发现它很慢.慢用Java标准.

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.

这篇关于如何评估Freemarker宏中的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆