Freemarker:创建下拉字段并从Map的键/值中设置其值和选项

时间:2013-07-19 12:00:23

标签: spring spring-mvc freemarker

如何在freemarker模板中创建下拉字段?下拉选项和值将从地图传递。这是从控制器

传递的地图
Map<String, Map<String, String>> codeTable = new HashMap<String,Map<String, String>>();
Map<String, String> codeTableValues = new HashMap<String,String>();
        codeTableValues.put("1", "US");
        codeTableValues.put("2", "UK");
        codeTableValues.put("3", "India");
        codeTableValues.put("4", "Ireland");
        codeTableValues.put("5", "Germany");
        codeTable.put("country", codeTableValues);

对于freemarker,我遇到spring.ftl并尝试使用formSingleSelect,但无法理解它。 FTL 代码:

<#elseif field.@type="select">
                <@spring.bind "codeTable.country" />
                <@spring.formSingleSelect "country", codeTable.country, "" />
            </#if>

异常

FreeMarker template error: Method public org.springframework.web.servlet.support.BindStatus org.springframework.web.servlet.support.RequestContext.getBindStatus(java.lang.String) throws java.lang.IllegalStateException threw an exception when invoked on org.springframework.web.servlet.support.RequestContext object "org.springframework.web.servlet.support.RequestContext@1479ef9" with arguments of types [java.lang.String,]. See cause exception. The failing instruction (FTL stack trace): ---------- ==> #assign status = springMacroRequestCo... [in template "spring.ftl" in macro "bind" at line 74, column 17] #else [in template "spring.ftl" in macro "bind" at line 73, column 9] @spring.bind "codeTable.country" [in template "index.ftl" at line 31, column 33] #elseif field.@type = "select" [in template "index.ftl" at line 30, column 25]

1 个答案:

答案 0 :(得分:0)

使用 spring.formSingleSelect 构建下拉列表。假设您有一个名为 Vacccine 的 Bean。

public class Vaccine {

    private Long id;
    
    private String name;
    
    private String companyName;
    
    private Integer country;
    
    // Getter & Setter

}

和国家地图如下...

Map<String, String> countryMap = new HashMap<>();
countryMap.put("1", "US");
countryMap.put("2", "UK");
countryMap.put("3", "India");
countryMap.put("4", "Ireland");
countryMap.put("5", "Germany");

然后你可以像下面这样绑定国家地图...

<@spring.formSingleSelect  'Vaccine.country', countryMap, 'class="form-control" ' />