Freemarker自定义方法变量

最近在项目开发中使用了freemarker,并在前台显示文本时遇到这样一个需求,当长度超过10个字时只显示出前面10个字,并在后面加...。这里就可以在freemarker中实现一个自定义方法变量。

实现自定义方法变量基本步骤:
1.先实现TemplateMethodModel或TemplateMethodModelEx接口(TemplateMethodModelEx 继承自TemplateMethodModel 接口,我这里使用的是TemplateMethodModelEx接口),再覆盖该接口的Object exec(java.util.List arguments)方法,该方法里写的就是我们自己想要实现的效果,当使用方法表达式调用一个方法(exec)时,实际上就是在执行这个exec方法,页面中方法表达式的参数就是该方法的参数,方法的返回值就是方法表达式的返回值。
2.new一个该方法变量的实例添加到freemarker的Configuration配置中。

例子代码:

/**
 * 截取显示字符串,当字符串长度超过指定长度时,显示截取部分加...
 */
public class StringSub implements TemplateMethodModelEx {

    @Override
    public Object exec(@SuppressWarnings("rawtypes") List args) throws TemplateModelException {
        if (args == null || args.size() < 2) {
            throw new RuntimeException("missing arg");
        }

        if (args.get(0) == null || args.get(1) == null) {
            return "";
        }

        SimpleScalar simpleScalar = (SimpleScalar) args.get(0);
        String content = simpleScalar.getAsString();
        SimpleNumber simpleNumber = (SimpleNumber) args.get(1);
        Integer length = simpleNumber.getAsNumber().intValue();

        if (content.length() > length) {
            content = content.substring(0, length);
            return content + "...";
        }

        return content;
    }

}

freemarker工具类(只显示部分代码):

public class FreemarkerUtil {
    public static final Configuration cfg = new Configuration();
    static {
        cfg.setDefaultEncoding("UTF-8");
        cfg.setTagSyntax(Configuration.AUTO_DETECT_TAG_SYNTAX);
        cfg.setNumberFormat("###########.##");
        cfg.setSharedVariable("StringSub", new StringSub());
    }

    public static String process(String template, Map<String, ?> model) throws Exception {
        StringWriter out = new StringWriter();
        String result = null;
        try {
            FreemarkerUtil.cfg.getTemplate(template + ".ftl").process(model, out);
            result = out.toString();
        } catch (Exception ex) {
            throw ex;
        } finally {
            StreamUtil.close(out);
        }
        return result;
    }
}

最终在前台页面使用:


转自:https://www.jianshu.com/p/f4c47ce5b3c5

猜你喜欢

转载自blog.csdn.net/daobuxinzi/article/details/109513911