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中加入以下代码即可: |