在freemarker的模板文件中调用自定义的方法

freemarker现有的一些内置函数不能满足我们的需求,这些内置函数包括:chunk, is_date, last, root, j_string, contains, is_hash, long, float, ends_with, namespace, matches, time, values, seq_last_index_of, uncap_first, byte, substring, is_transform, web_safe, groups, seq_contains, is_macro, index_of, word_list, int, is_method, eval, parent, xml, number, capitalize, if_exists, rtf, node_type, double, is_directive, url, size, default, is_boolean, split, node_name, is_enumerable, seq_index_of, is_sequence, sort, is_node, sort_by, left_pad, cap_first, interpret, children, node_namespace, chop_linebreak, date, short, last_index_of, is_collection, ancestors, length, trim, datetime, is_string, reverse, c, keys, upper_case, js_string, has_content, right_pad, replace, is_hash_ex, new, is_number, is_indexable, lower_case, string, exists, html, first, starts_with

但freemarker可以自定义方法来达到这一目的:实现的步骤为:
写一个类继承TemplateMethodModel,比如说:
public class TruncateTemplateMethodModel implements TemplateMethodModel {
    public Object exec(List arguments) throws TemplateModelException {
        return arguments.get(0).toString().substring(0,1);
    }
}
然后:
            Map root = new HashMap();
            root.put("truncate",new TruncateTemplateMethodModel();
            Template temp = cfg.getTemplate("a.ftl");
            StringWriter out = new StringWriter();
            temp.process(root, out);
            out.flush();
            System.out.println(out.getBuffer().toString());
a.ftl为:${truncate("abc")}
运行后将会输出: a

若与spring集成的话,也很简单,只要在:*-servlet.xml中加入以下代码即可:
<bean id="viewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
        <property name="suffix" value=".ftl"/>
        <property name="contentType" value="text/html;charset=UTF-8"/>
        <property name="exposeRequestAttributes" value="true"/>
        <property name="exposeSessionAttributes" value="true"/>
        <property name="attributesMap">
          <map>
            <entry key="truncate"><bean class="com.rj8g.linkage.renba.web.TruncateTemplateMethodModel" /></entry>
          </map>
        </property>
    </bean>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值