freemarker寫select元件(三)
阿新 • • 發佈:2018-12-24
freemarker寫select元件
1、巨集定義
<#macro select id datas value="" key="" text=""> <select id="${id}" name="${id}"> <option>---請選擇---</option> <#list datas as data> <#if key!=""> <#if value == data[key]?string> <option value="${data[key]}" selected>${data[text]}</option> <#else> <option value="${data[key]}">${data[text]}</option> </#if> <#else> <#if value == data> <option value="${data}" selected>${data}</option> <#else> <option value="${data}">${data}</option> </#if> </#if> </#list> </select> </#macro>
2、封裝類
/** * @Title:User.java * @Package:com.you.freemarker.model * @Description: * @author:Youhaidong(遊海東) * @date:2014-6-26 下午10:28:01 * @version V1.0 */ package com.you.freemarker.model; /** * 類功能說明 * 類修改者 修改日期 * 修改說明 * <p>Title:User.java</p> * <p>Description:遊海東個人開發</p> * <p>Copyright:Copyright(c)2013</p> * @author:遊海東 * @date:2014-6-26 下午10:28:01 * @version V1.0 */ public class User { /** * 使用者號 */ private int userNo; /** * 使用者姓名 */ private String userName; /** * 使用者年齡 */ private int userAge; /** * @return the userNo */ public int getUserNo() { return userNo; } /** * @param userNo the userNo to set */ public void setUserNo(int userNo) { this.userNo = userNo; } /** * @return the userName */ public String getUserName() { return userName; } /** * @param userName the userName to set */ public void setUserName(String userName) { this.userName = userName; } /** * @return the userAge */ public int getUserAge() { return userAge; } /** * @param userAge the userAge to set */ public void setUserAge(int userAge) { this.userAge = userAge; } /** * <p>Title:</p> * <p>Description:</p> * @param userNo * @param userName * @param userAge */ public User(int userNo, String userName, int userAge) { super(); this.userNo = userNo; this.userName = userName; this.userAge = userAge; } /** * <p>Title:</p> * <p>Description:</p> */ public User() { super(); } }
3、頁面引入
<@items.select id="user" datas=users key="userNo" text="userName"/>
4、Junit測試方法
/** * * @Title:testSelect * @Description: * @param: * @return: void * @throws */ @Test public void testSelect() { List<User> users = Arrays.asList(new User(1,"張三丰",25), new User(2,"李思思",22), new User(3,"趙武",23), new User(4,"劉雪",20), new User(5,"朱顧",21), new User(6,"趙武",23), new User(7,"吳語",24), new User(8,"血玉",21)); root.put("users", users); studentPrint("address.ftl"); studentFile("address.ftl","address.html"); }
5、測試結果
(1)控制檯列印
<select id="user" name="user">
<option>---請選擇---</option>
<option value="1">張三丰</option>
<option value="2">李思思</option>
<option value="3">趙武</option>
<option value="4">劉雪</option>
<option value="5">朱顧</option>
<option value="6">趙武</option>
<option value="7">吳語</option>
<option value="8">血玉</option>
</select>
(2)頁面顯示