Freemarker 自定義標籤 實現TemplateDirectiveModel

1  自定義標籤須要實現TemplateDirectiveModel這個接口中的execute方法  實例代碼以下 html

public class UserListDirective implements TemplateDirectiveModel{
	
	@Autowired
	private UserDAO  userDao;
	@Override
	public void execute(Environment env, Map params, TemplateModel[] loopVars,
			TemplateDirectiveBody body) 
                      throws TemplateException, IOException {
		String name = params.get("name").toString();
		List<User> userlist = userDao.findByProperty("name", name);

		env.setVariable("userList", getBeansWrapper().wrap(userlist));
		body.render(env.getOut());
	}
	
	public static BeansWrapper getBeansWrapper(){
		BeansWrapper beansWrapper = 
                         new BeansWrapperBuilder(Configuration.VERSION_2_3_21).build();
		return beansWrapper;
	}
}



2 配置 UserListDirective 到spring  bean xml中 java

<bean id="userListDirective" class="com.action.directive.UserListDirective"></bean>
3 將spring bean 設置到freemarkerConfig全局變量中去。
<bean id="freemarkerConfig2"
        class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
        <property name="templateLoaderPath" value="/" />
        <property name="freemarkerVariables">
            <map >
                <entry key="userListDirective" value="userListTag" />
            </map>
        </property>
        <property name="freemarkerSettings">
            <props>
                <prop key="template_update_delay">0</prop>
                <prop key="defaultEncoding">UTF-8</prop>
                <prop key="url_escaping_charset">UTF-8</prop>
                <prop key="locale">zh_CN</prop>
                <prop key="boolean_format">true,false</prop>
                <prop key="datetime_format">yyyy-MM-dd HH:mm:ss</prop>
                <prop key="date_format">yyyy-MM-dd</prop>
                <prop key="time_format">HH:mm:ss</prop>
                <prop key="number_format">0.######</prop>
                <prop key="whitespace_stripping">true</prop>
            </props>
        </property>
    </bean>
4 ftl文件中的訪問方式


<@userListTag name="zhangsan">
    <#if userList?? && userList?size gt 0>
        <#list userList as user>
            <a href="">${user.name}</a>
        </#list>
    </#if> 
</@userListTag>

5 freemarker 遍歷 map web

第一種方式(2.3.21版本以前好像能夠用) spring

<#list testMap?keys as testKey>  
    < option value="${testKey}" >  
        ${testMap.get(testKey)}  
    </option>  
</#list>
第二種方式

<#list testMap.keySet() as testKey>  
    < option value="${testKey}" >  
        ${testMap.get(testKey)}  
    </option>  
</#list>
相關文章
相關標籤/搜索