欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Freemarker 自定义标签 实现TemplateDirectiveModel

程序员文章站 2022-06-09 07:52:15
...

1  自定义标签需要实现TemplateDirectiveModel这个接口中的execute方法  实例代码如下

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中

<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

第一种方式(2.3.21版本之前好像可以用)

<#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>





转载于:https://my.oschina.net/zb0423/blog/346695