简体   繁体   English

创建自定义Grails Tag Lib生成代码

[英]Create custom Grails Tag Lib the generates code

Is there any documentation regarding how to create a custom grails tag that generated groovy code similar to "<g:if>" and "<g:else>"? 是否有任何有关如何创建自定义grails标记的文档,该标记生成类似于“ <g:if>”和“ <g:else>”的常规代码?

Using the normal grails taglib, I'm able to generate html or raw output, but I'm looking to output code that can be interpreted similar to how the if and else tags work. 使用普通的grails taglib,我能够生成html或原始输出,但是我希望输出的代码可以被解释,类似于if和else标签的工作方式。

Here's a sample of the Grails source code for the "if" tag: 以下是“ if”标签的Grails源代码示例:

@Override
protected void outputStartTag(String envExpression, String testExpression) {
    out.print("if(");
    out.print(envExpression);
    out.print(" && ");
    out.print(testExpression);
    out.println(") {");
}

How can I do something similar in my own taglib prefix. 我该如何在自己的taglib前缀中做类似的事情。

Example: 例:

<mine:doSomethingCool key="foo">This text is conditionally shown</mine:doSomethingCool>

In addition to hiding complex logic, I would like this ability so I can use the <g:else> tag after my custom tag. 除了隐藏复杂的逻辑之外,我还希望具有此功能,因此可以在自定义标签之后使用<g:else>标签。

In general, I would like another tool in my toolbox in addition to the current taglib format. 通常,除了当前的taglib格式外,我还希望在工具箱中使用其他工具。

If for example you only want to render the conditional text when key == 'foo' , you could do that like this: 例如,如果您只想在key == 'foo'时呈现条件文本,则可以这样做:

class SomethingTagLib {

    static namespace = "ns"

    def doSomethingCool = { attrs, body ->
        if (attrs.key == 'foo') {
            out << body()
        }
    }
}

You could then use this tag like so: 然后,您可以像下面这样使用此标记:

<ns:doSomethingCool key="foo">This text is conditionally shown<ns:doSomethingCool>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM