Search code examples
grailsgsp

Grails passing parameters between taglibs and javascripts


I'm creating a widget with a tag lib, which depends on a lot of javascript being pushed to the browser. I have it written all in the taglib as text, and push it with out << , but I think it would be cleaner if I pulled out the script and included it as an asset. However, having some trouble figuring out how to separate the javascript from the grails code in the taglib

Simplified example of what I am trying to do -- lets say a 'name' tag that shows the user name, but when you click it alerts the users Id:

As a tag I could write:

class FooTagLib {
    static encodeAsForTags = [tagName: [taglib:'html'], otherTagName: [taglib:'none']]
    static namespace = 'foo'
    def name = {attrs, body ->
        out << "<p id = ${attrs.uid}>${attrs.username}</p>"
        out << "<script type='text/javascript'>"
        out << """
\$('#{$attrs.uid}.click( function() {
alert("ID for user ${attrs.username} is ${attrs.uid}); });
"""
    }
}

And then in my gsp I could just write:a

<foo:name username="${user.name}" uid="${user.id}"></foo:name>

What I can't figure out is how to extract the click function out of the taglib into a javascript library, so I can turn FooTagLib into this: How do I pass attrs.username and attrs.uid so it is accessible in the javascript file?

 class FooTagLib {
        static encodeAsForTags = [tagName: [taglib:'html'], otherTagName: [taglib:'none']]
        static namespace = 'foo'
        def name = {attrs, body ->
            out << "<p id = ${attrs.uid}>${attrs.username}</p>"
            out << "<asset:  type='text/javascript'>"
            out << "<asset:javascript src='footag.js'/>
         }
    }

Solution

  • One way I accomplish this is using Jquery data.

    Write your tag like this:

    out << "<p id='my-p-with-data' data-id='${attrs.uid}' data-name='${attrs.username}'>${attrs.username}</p>"
    

    Your rendered HTML is:

    <p id='my-p-with-data' data-id='5' data-name='John Doe'>John Doe</p>
    

    And then, you need to use JS:

    alert("ID for user "+$('#my-p-with-data').data( 'name' ) + " is " + $('#my-p-with-data').data( 'id' ))
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <p id='my-p-with-data' data-id='5' data-name='John Doe'>John Doe</p>