侧边栏壁纸
  • 累计撰写 781 篇文章
  • 累计创建 1 个标签
  • 累计收到 1 条评论
标签搜索

自定义指令(示例)

Dettan
2021-04-10 / 0 评论 / 0 点赞 / 92 阅读 / 2,485 字
温馨提示:
本文最后更新于 2022-04-30,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。
调用
<@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(&quot;blockNodes&quot;)) {
        DefaultObjectWrapperBuilder builder = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_25);
        String method = map.get(&quot;blockNodes&quot;).toString();
        switch (method) {
            case &quot;tagsList&quot;:
                // 将数据对象转换成对应的TemplateModel
                TemplateModel tm = builder.build().wrap(&quot;&quot;);
                environment.setVariable(&quot;tagsList&quot;, tm);
                break;
            default:
                break;
        }

    }
    Writer out = environment.getOut();
    out.append(&quot;&lt;@test title = \&quot;fds\&quot; /&gt;&quot;);

    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();
0

评论区