• 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>
  • 相关阅读:
    C#写的操作系统
    FPS游戏:实现狙击子弹加速
    内表的一些操作例子(工作区赋值使用了新语法)
    SAP MM模块相关透明表收集
    简单的ALV显示例子
    拼接和前导零用法
    LOOP AT GROUP语法练习
    RFC函数的初步使用同步
    excel保存时出现“请注意,您的文档的部分内容可能包含了文档检查器无法删除的个人信息”
    Abap内表
  • 原文地址:https://www.cnblogs.com/dixinyunpan/p/5786995.html
Copyright © 2020-2023  润新知