列表中的Freemarker if-else(范围)

时间:2012-09-12 09:30:47

标签: templates freemarker template-engine

在列表中我想要合并一个if host.machine == 1然后action = Set else action = Create

我想要以下输出 Type:Machine;Action:Set;Attributes[Name:machine1~NodeManager.ListenAddress:10.104.17.70~NodeManager.ListenPort:5558]<BR> Type:Machine;Action:Create;Attributes[Name:machine2~NodeManager.ListenAddress:10.104.17.71~NodeManager.ListenPort:5558]<BR>

我的数据

hosts:[{"name": "trfuoemlpa004v", "node": 0, "server": 1, "Machine": 1, "ManagedPort": "7002", "SSLPort": 1081}, {"name": "trfuoemlpa007v", "node": 1, "server": 2, "Machine": 2, "ManagedPort": "7002", "SSLPort": 1081}]

我让不同的模板都失败了:

1) <#list hosts as host><#assign machine=${host.machine}><#if machine == 1><#assign action="Set"><#else><#assign action="Create"></#if>Type:Machine;Action:${action};Attributes[Name:${host.machine}~NodeManager.ListenAddress:${host.name}~NodeManager.ListenPort:${nodeManagerPort}]<BR></#list>

**freemarker.core.ParseException: Encountered "}" at line 8, column 40 in J2EE.properties. Was expecting one of:">" ... "." ... "[" ... "(" ... "?" ... "!" ... <TERMINATING_EXCLAM> ... "??" ... "+" ...**

2) <#list hosts as host><#if host.machine == 1><#assign action="Set"><#else><#assign action="Create"></#if>Type:Machine;Action:${action};Attributes[Name:${host.machine}~NodeManager.ListenAddress:${host.name}~NodeManager.ListenPort:${nodeManagerPort}]<BR></#list>

**freemarker.core.InvalidReferenceException: Expression host.machine is undefined**

3) <#list hosts as host><#if $host.machine} == 1 > ...

**freemarker.core.ParseException: Encountered "}" at line 8, column 40 in J2EE.properties. Was expecting one of:">" ... "." ... "[" ... "(" ... "?" ... "!" ... <TERMINATING_EXCLAM> ... "??" ... "+" ...**

1 个答案:

答案 0 :(得分:0)

第二个是正确的,因为$在 FreeMarker表达式中没有特殊含义(在字符串文字内部除外)。 ${expression}仅用于将表达式的值插入静态文本(或字符串文字)。错误消息表示host变量没有名为machine的子变量或null。在最后一种情况下,您必须为其指定一些默认值,例如host.machine!0

顺便说一下,这个:

<#if host.machine == 1><#assign action="Set"><#else><#assign action="Create"></#if>Type:Machine;Action:${action};

可以这样写:

Type:Machine;Action:<#if host.machine == 1>Set<#else>Create</#if>;