Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grails g:select add HTML 5 data attributes

Tags:

html

grails

I want to load extra data into each select option of Grails g:select taglib. Required output is like the following:

<select id="select">
  <option value="1" data-foo="dogs">this</option>
  <option value="2" data-foo="cats">that</option>
  <option value="3" data-foo="gerbils">other</option>
</select>

I am not able to find a way to add the extra data to the taglib using the data attributes of HTML 5. So how to achieve the similar output?

like image 809
Chetan Avatar asked Apr 11 '16 14:04

Chetan


1 Answers

You can do this by (mis-)using a closure to render the value (called optionKey in Grails select taglib) of the select options:

<g:select from="${books}"
      optionKey="${{ book -> "${book.id}\" data-author=\"${book.author.name}"}}"
      optionValue="title"
      name="selectedBook"/>

This will render the options with a data-author attribute:

<option value="1" data-author="Johann Wolfgang von Goethe">Faust</option>

This works at least in Grails 2.4.4 and Grails 3.1.5.

like image 97
deflomu Avatar answered Nov 10 '22 13:11

deflomu