在 tagLib 中使用方法调用语法时,如何将 id 传递给 link?

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

我有一个标签定义:

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")
}

我希望 HTML 元素中的 id="actual-id" 出现在输出中,但事实并非如此。

答案是,(对于遇到此问题的任何其他人):

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

在 ApplicationTagLib 的源代码中找到 https://searchcode.com/codesearch/view/72308377/

这是因为 id 属性(以及所有其他属性)用于 link href 本身。

对于 g:link Taglib 中使用的 idelementId 之间的初学者(有时)来说,这是相当混乱的。

各种标签库中的 id 属性,如 g:formg:linkg:textField 等,不适用于任何 [=36] 的 id 属性=] 标签,而是引用域 class 的标识或 id 字段。因此,如果您在任何这些标签库中使用 id,它将用于 /$controller/$action/$id URL 映射(默认映射)。

所以最终,要生成具有 id 属性的 <a> 标签,您需要使用 elementId 代替(正如您已经回答的那样)。

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']