Freemarker 自定义标签 实现TemplateDirectiveModel

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>
posted @ 2016-08-19 11:35  涤新云  阅读(6973)  评论(0编辑  收藏  举报