freemarker自定义标签的写法和使用

首先是下载freemarker的jar包:下载地址

写标签类(需要继承TemplateDirectiveModel接口重写execute方法)

package freemarker;

import java.io.IOException;

import java.io.Writer;

import java.util.Map;

import freemarker.core.Environment;

import freemarker.template.TemplateDirectiveBody;

import freemarker.template.TemplateDirectiveModel;

import freemarker.template.TemplateException;

import freemarker.template.TemplateModel;

import freemarker.template.TemplateNumberModel;

publicclass LabelDirective implementsTemplateDirectiveModel {   @Override   

      publicvoid execute(Environment env, Map params,TemplateModel[] loopVars,           TemplateDirectiveBody body) throws TemplateException, IOException {       

Writer out =env.getOut(); //将模版里的数字参数转化成int类型的方法,,其它类型的转换请看freemarker文档       

TemplateModel paramValue = (TemplateModel)params.get("num");        int num= ((TemplateNumberModel)paramValue).getAsNumber().intValue();                out.write("Akishimo num=" +params.get("num")+"的类型为:"+paramValue.getClass());       

if (body != null) {           

body.render(env.getOut());       

}else{

thrownew RuntimeException("标签内部至少要加一个空格");       }    }}

写配置和测试的类:

 1package freemarker; 2 3

import java.io.BufferedWriter; 4

import java.io.File;5

import java.io.FileOutputStream; 6

import java.io.OutputStreamWriter; 7

import java.io.Writer;8

import java.util.HashMap; 9

import java.util.Map;1011

import freemarker.template.Configuration;12

import freemarker.template.DefaultObjectWrapper;13

import freemarker.template.Template;1415

publicclass Test {1617    

publicstaticvoid main(String[] args) throws Exception {1819        Configuration cfg = new Configuration();20         //将写好的标签加入,起名叫label21        

cfg.setSharedVariable("label", new LabelDirective());22        cfg.setDirectoryForTemplateLoading(newFile("temp"));23         cfg.setObjectWrapper(new DefaultObjectWrapper());2425        Template temp = cfg.getTemplate("list.ftl");2627        

Map root = newHashMap();28        

root.put("user", "rzy");2930        /* Writer out = newOutputStreamWriter(System.out); */3132       

File htmlFile = newFile("E:/a.html");33       

Writer out = newBufferedWriter(new OutputStreamWriter(new FileOutputStream(htmlFile), "UTF-8"));3435        

temp.process(root, out);36        

out.flush();37    }38 }

模版list.ftl先这么写

<!DOCTYPE html PUBLIC "-//W3C//DTDXHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><htmlxmlns="http://www.w3.org/1999/xhtml"><head><metahttp-equiv="Content-Type" content="text/html;charset=utf-8" /><title>无标题文档</title></head><body><h1>${user}自定义标签输出结果</h1><br/><@label num=12></@label></body></html>

运行后打开e盘里面生成的a.html结果为:

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 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、付费专栏及课程。

余额充值