# link

## Purpose

Creates an html anchor tag with the `href` set based on the parameters specified.

## Examples

Example controller for an application called "shop":

    class BookController {
         def list = { [ books: Book.list( params ) ] }
         def show = { [ book : Book.get( params['id'] ) ] }
    }

Example usages for above controller:

    <g:link action="show" id="1">Book 1</g:link>
    <g:link action="show" id="${currentBook.id}">${currentBook.name}</g:link>
    <g:link controller="book">Book Home</g:link>
    <g:link controller="book" action="list">Book List</g:link>
    <g:link url="[action:'list',controller:'book']">Book List</g:link>
    <g:link action="list" params="[sort:'title',order:'asc',author:currentBook.author]">
         Book List
    </g:link>
    <g:link controller="book" absolute="true">Book Home</g:link>
    <g:link controller="book" base="http://admin.mygreatsite.com">Book Home</g:link>

Example as a method call in GSP only:

    <%= link(action:'list',controller:'book') { 'Book List' }%>

Results in:

    <a href="/shop/book/list">Book List</a>

## Description

Attributes

- `action` (optional) - the name of the action to use in the link, if not specified the default action will be linked
- `controller` (optional) - the name of the controller to use in the link, if not specified the current controller will be linked
- `elementId` (optional) - this value will be used to populate the `id` attribute of the generated href
- `id` (optional) - the id to use in the link
- `fragment` (optional) - The link fragment (often called anchor tag) to use
- `mapping` (optional) - The named URL mapping to use to rewrite the link
- `params` (optional) - a map containing request parameters
- `url` (optional) - a map containing the action, controller, id etc.
- `absolute` (optional) - If set to "true" will prefix the link target address with the value of the grails.serverURL property from Config, or http://localhost:<port> if no value in Config and not running in production.
- `base` (optional) - Sets the prefix to be added to the link target address, typically an absolute server URL. This overrides the behaviour of the `absolute` property, if both are specified.

## Source

Show Source

    def link = { attrs, body ->        def writer = getOut()
            def elementId = attrs.remove('elementId')
            writer <<  "<a href=\"${createLink(attrs).encodeAsHTML()}\""
            if(elementId) {
               writer << " id=\"${elementId}\""
            }        writer << "${attrs.collect {k, v -> " $k=\"$v\"" }.join('')}>"
            writer << "${body()}</a>"
        }