美文网首页
Freemarker 自定义指令/函数 踩坑

Freemarker 自定义指令/函数 踩坑

作者: 马克_唐卡 | 来源:发表于2020-08-28 11:29 被阅读0次

    需求:

    • 使用模版引擎讲待处理的模版中的变量替换为最终值
    • 模版中需要使用到 list 循环。需要根据数据列表生成数量不定的结果
    • 模版中需要使用到 base64 编码,且需要支持嵌套。base64 编码中需要支持变量替换

    base64( base64( "data1": ${data1 } ): base64( "data2": ${data2} ) )

    开发环境

    • Springboot Maven Kotlin k8s

    需求调研

    • 搜索了常用的模版引擎,尝试使用了 jinjava、Freemarker, 由于 jinjava 没有找到足够的功能来支持需求,最终选择更为常用的 Freemarker.

    需求实现

    • 添加依赖
    <!-- freemarker -->
            <dependency>
                <groupId>org.freemarker</groupId>
                <artifactId>freemarker</artifactId>
                <version>2.3.30</version>
            </dependency>
    
    • 新建一个自定义(实现base64编码)方法类
    class Base64Method : TemplateMethodModelEx {
        override fun exec(data: MutableList<Any?>): Any {
            return String(Base64.getEncoder().encode(data[0].toString().toByteArray(Charsets.UTF_8).clone()))
        }
    }
    
    • 模版操作
    @Test
        @Transactional
        fun tempalteTest() {
            val stringLoader = StringTemplateLoader()
            val templateValue: String = "<#list data1 as dataType1>\n" +
                    "'type1://\${base64(\"\${data1.userName}:\${data1.password}\")}'\n" +
                    "</#list>\n" +
                    "<#list data2 as dataType2>\n" +
                    "'type2://\${base64\"{\"userName\":\"\${data2.nodeName}\",\"password\":\"\${data2.password}\"}\")}'\n" +
                    "</#list>\n" +
                    "<#list data3 as dataType2>\n" +
                    "'type3://\${base64(\"\${data3.userName}@\${data3.password}\")}'\n" +
                    "</#list>"
            stringLoader.putTemplate("myTemplate", templateValue)
            val configuration = Configuration(Configuration.getVersion())
            configuration.defaultEncoding = "utf-8"
            configuration.setSharedVariable("base64", Base64Method());
    //        configuration.setSharedVariable("base66", Base64Directive()); // 不满足需求,遗弃
            configuration.templateLoader = stringLoader
    
            val template = configuration.getTemplate("myTemplate", "utf-8")
    
            //向数据集中添加数据
            val dataModel: MutableMap<String, MutableList<Map<String, String>>> = mutableMapOf()
            val type1: MutableList<Map<String, String>> = mutableListOf()
            val type2: MutableList<Map<String, String>> = mutableListOf()
            val type3: MutableList<Map<String, String>> = mutableListOf()
    
            val apList = HttpUtil.get("https://xxx.xxx") // 获取后端数据
    
            // 根据后端结果apList 初始化数据
            // type1 初始化
            // type2 初始化
            // type3 初始化
    
            dataModel["type1"] = type1
            dataModel["type2"] = type2
            dataModel["type3"] = type3
    
            val out: Writer = StringWriter()
            // 第七步:调用模板对象的process方法输出文件。
            template.process(dataModel, out)
            // 第八步:关闭流。
            var test2 = out.toString()
            out.flush()
            out.close()
        }
    

    未能实现部分

    • 嵌套实现

    踩的坑

    • 刚开始使用 TemplateDirectiveModel 自定义指令的方式,如果待编码的内容中出现变量,就会出现 base64 编码的是一段一段的,也就是先每一小段编码,在拼接成完成的。但我需要的效果是先拼接成完整的再进行base64。即便是这样,我也想如果能拿到待编码 list 的长度,那等拼接到最后一个再编码也行,但并不能拿到这个 list,放弃。
    • 在使用 TemplateMethodModelEx 时,如果待编码内容中有使用双引号这类字符,需要使用 \ 来转义,否则会出现数据丢失问题。
    • 在测试嵌套时,方法内无法使用 <#list> 循环,故最后的解决方案是:再结果的基础上自行 base64。

    如有错误,请大佬指定,这是一种不完整的解决方式,正在寻求更好的解决方案~

    相关文章

      网友评论

          本文标题:Freemarker 自定义指令/函数 踩坑

          本文链接:https://www.haomeiwen.com/subject/dvnksktx.html