简体   繁体   中英

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>"?

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.

Here's a sample of the Grails source code for the "if" tag:

@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.

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.

In general, I would like another tool in my toolbox in addition to the current taglib format.

If for example you only want to render the conditional text when key == 'foo' , you could do that like this:

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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