调用
<@BlockList title="fdsaf" fdsaf="fsdsd">
<p>fdsafd</p>
</@BlockList>
<@test title = "fds" />
定义
•
map 里是 title="fdsaf" fdsaf="fsdsd" 转换成map
•
environment 是环境,
•
下面的输出会添加到输出内容的前面. 但是 注意 : 这里输出的东西已经算是最终文本,freemark不会再解析. 具体怎么让freemark再解析我也没找到怎么弄.
Writer out = environment.getOut();
out.append("<@test title = \"fds\" />");
•
templateDirectiveBody 是自定义标签里包含的东西,没什么用,不可操作,唯一的作用就是最后调用一下然后往后执行.
package ljj;
import freemarker.core.Environment;
import freemarker.template.*;
import ljj.api.type.BlockNode;
import java.io.IOException;
import java.io.Writer;
import java.util.Map;
public class NotionBlockListTagDirective implements TemplateDirectiveModel {
private BlockNode[] blockNodes;
@Override
public void execute(Environment environment, Map map, TemplateModel[] templateModels, TemplateDirectiveBody templateDirectiveBody) throws TemplateException, IOException, IOException {
if (map.containsKey("blockNodes")) {
DefaultObjectWrapperBuilder builder = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_25);
String method = map.get("blockNodes").toString();
switch (method) {
case "tagsList":
// 将数据对象转换成对应的TemplateModel
TemplateModel tm = builder.build().wrap("");
environment.setVariable("tagsList", tm);
break;
default:
break;
}
}
Writer out = environment.getOut();
out.append("<@test title = \"fds\" />");
templateDirectiveBody.render(out);
}
}
配置
Configuration cfg = new Configuration(Configuration.VERSION_2_3_29);
ClassLoader classLoader = cfg.getClass().getClassLoader();
URL resource = classLoader.getResource("htmlTemplate/");
if (null == resource) return;
String jsonPath = URLDecoder.decode(resource.getPath(), "UTF-8");
// 如果运行在windows上,获取到的path会变成"/E:/Convert...",直接使用的话会报错(会提示:the char ':' is illegal),需要处理一下
System.out.println(jsonPath);
cfg.setDirectoryForTemplateLoading(new File(jsonPath.contains(":") ? jsonPath.substring(1) : jsonPath));
Template temp = cfg.getTemplate("page.ftl");
//输出到console
Writer out = new OutputStreamWriter(System.out);
HashMap<String, Object> dataModel = new HashMap<>();
dataModel.put("blocksTemplate", sb.toString());
//自定义标签
cfg.setSharedVariable("BlockList", new NotionBlockListTagDirective());
temp.process(dataModel, out);
输出到字符串
StringWriter stringWriter = new StringWriter();
temp.process(dataModel, stringWriter);
String pageTemplate = stringWriter.toString();
评论区