chim
chim

Reputation: 8573

How do I pass an id to a link when using the method call syntax in a tagLib?

I've got a tag definition:

def myCustomLink =  { attrs, body ->
    def url = complexUrl(attrs.whatever)
    def linkAttrs = [url: url, class:'css-class', id: 'actual-id']
    out << g.link(linkAttrs, body() ?: "Book a service")
}

I'd expect id="actual-id" in the HTML element to turn up in the output, but this isn't the case.

Upvotes: 1

Views: 133

Answers (2)

Shashank Agrawal
Shashank Agrawal

Reputation: 25797

It's quite confusing for beginners (sometimes) between id & elementId used in g:link Taglib.

The id attribute in various Taglibs like g:form, g:link, g:textField etc. is not for the id attribute of any HTML tag, instead this is the Identity or id field referencing a domain class. So if you use id in any of those taglibs, it's gonna be used in /$controller/$action/$id URL mapping (the default mapping).

So ultimately, to generate <a> tag with id attribute, you need to use elementId instead (as you already answered).

http://docs.grails.org/3.2.9/ref/Tags/link.html

elementId (optional) - this value will be used to populate the id attribute of the generated href

Map linkAttrs = [url: url, class: 'css-class', elementId: 'actual-id']

Upvotes: 1

chim
chim

Reputation: 8573

The answer is, (for anyone else who has this issue):

// Use the elementId attribute to pass an id for the anchor tag itself.
def linkAttrs = [url: url, class:'css-class', elementId: 'actual-id']

Found in the source code for ApplicationTagLib https://searchcode.com/codesearch/view/72308377/

This is because the id attribute (and all other attributes) are used in the link href itself.

Upvotes: 1

Related Questions