首页 > 解决方案 > 如何在 FreeMarker 中嵌套相同的自定义指令?

问题描述

这是我的模板:

<@base64>head://<@base64>{"add":"addr","aid":"0","host":"sefse.sdf.xyz"}</@base64></@base64>

这是我的指令:

class Base64Directive : TemplateDirectiveModel {


    @Throws(TemplateException::class, IOException::class)
    override fun execute(env: Environment,
                         params: Map<*, *>, loopVars: Array<TemplateModel?>,
                         body: TemplateDirectiveBody?) { // Check if no parameters were given:
        if (!params.isEmpty()) {
            throw TemplateModelException(
                    "This directive doesn't allow parameters.")
        }
        if (loopVars.size != 0) {
            throw TemplateModelException(
                    "This directive doesn't allow loop variables.")
        }
        // If there is non-empty nested content:
        if (body != null) {
            // Executes the nested body. Same as <#nested> in FTL, except
            // that we use our own writer instead of the current output writer.
            body.render(Base64FilterWriter(env.out))
        } else {
            throw RuntimeException("missing body")
        }
    }

    /**
     * A [Writer] that transforms the character stream to upper case
     * and forwards it to another [Writer].
     */
    private class Base64FilterWriter internal constructor(out: Writer) : Writer() {
        private val out: Writer = out
        @Throws(IOException::class)
        override fun write(cbuf: CharArray, off: Int, len: Int) {
            var transformedCbuf = String(Base64.getEncoder().encode(String(cbuf).toByteArray(Charsets.UTF_8).clone()))
            out.write(transformedCbuf)
        }

        @Throws(IOException::class)
        override fun flush() {
            out.flush()
        }

        @Throws(IOException::class)
        override fun close() {
            out.close()
        }

    }
}

有两个相互嵌套的指令。当我运行我的代码时,它无法从内部编译指令对(<@base64>{"add":"addr","aid":"0","host":"sefse.sdf.xyz"}/@ base64)到外部(<@base64>head://base64-after/@base64)。

我怎样才能使这个编译工作从内到外?

标签: freemarkerdirective

解决方案


推荐阅读