开发者

Spring MVC + FreeMarker: How to render option tag?

开发者 https://www.devze.com 2023-01-06 12:31 出处:网络
The Spring 3 MVC docs state that option tags can be rendered like this: <tr> <td>Country:</td>

The Spring 3 MVC docs state that option tags can be rendered like this:

<tr>
      <td>Country:</td>
      <td>
          <form:select path="country">
              <form:options items="${countryList}" itemValue="code" itemLabel="name"/>
          </form:select>
      &开发者_运维技巧lt;/td>
</tr>

I am using FreeMarker with Spring MVC, so I interpret this as:

<tr>
    <td>Place:</td>
    <td>
        <@form.select path="place">
            <@form.options items="${places}" itemValue="id" itemLabel="name"/>

        </@form.select>
    </td>
</tr>

When I hit the page I get the following exception:

freemarker.core.NonStringException: Error on line 40, column 73 in event.ftl
Expecting a string, date or number here, Expression places is instead a freemarker.template.SimpleSequence

What should I use instead of ${places} in my FreeMarker template so that the above works?

Thanks.


I was looking for exactly the same thing. I've no idea why this isn't included in Spring's Freemarker macro library, but fortunately enough it's quite easy to implement: Best practice would be to start your own macro library (say mylib.ftl for example) and put the macro there:

<#macro selectOptions path options key value>
  <@spring.bind path/>
  <select id="${spring.status.expression}" name="${spring.status.expression}">
    <#list options as option>
      <option value="${option[key]?html}"<@spring.checkSelected option[key]/>>${option[value]?html}</option>
    </#list>
  </select>
</#macro>

You can then use your new macro in your Freemarker template like so:

<#import "/mylib.ftl" as mylib />
...
<@mylib.selectOptions "country" countryList "code" "name" />

HTH


You could try the following (not tested personally)

<@form.select path="place">
    <#list Request.places as place>
       <@form.option value="${place}" label="name" />
    </#list>
</@form.select>

Hope this helps!


a little bit weird but it works.

  • remove ${"places"} and use it straigh as places
  • remove the itemid and let spring handle it for you

so you will have

<@form.select path="place">
   <@form.options items=places itemLabel="name"/>

</@form.select>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号