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

 

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 Spring Boot 中使用 Freemarker 自定义标签,可以通过以下步骤实现: 1. 创建一个自定义标签类,继承 `freemarker.template.TemplateDirectiveModel` 接口,并实现其中的 `execute` 方法,该方法用于处理自定义标签的逻辑。 ```java @Component public class CustomTagDirective implements TemplateDirectiveModel { @Autowired private UserService userService; // 举例注入一个服务类 @Override public void execute(Environment environment, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { // 处理自定义标签逻辑,可以使用 environment、params、body 等参数 String userId = params.get("userId").toString(); User user = userService.getUserById(userId); environment.getOut().write(user.getName()); } } ``` 2. 在 Spring Boot 的配置文件中注册自定义标签类。 ```java @Configuration public class FreemarkerConfig { @Autowired private CustomTagDirective customTagDirective; @Bean public FreeMarkerConfigurer freeMarkerConfigurer() { FreeMarkerConfigurer configurer = new FreeMarkerConfigurer(); configurer.setTemplateLoaderPath("classpath:/templates"); Map<String, Object> variables = new HashMap<>(); variables.put("customTag", customTagDirective); configurer.setFreemarkerVariables(variables); return configurer; } } ``` 3. 在 Freemarker 模板中使用自定义标签。 ```html <#assign userId = "1" /> <@customTag userId=userId /> ``` 在以上代码中,我们首先通过 `<#assign>` 定义了一个变量 `userId`,然后通过 `<@customTag>` 调用自定义标签,并将 `userId` 作为参数传入。 这样就可以在 Spring Boot 中使用自定义Freemarker 标签了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值