Search code examples
javascriptgrailsgsp

How to make GSP tag generate code on one line?


I am dynamically adding a select box inside a div element with the following code:

$('#worker').html('<g:select class = "dropdown" name="worker" from="${workers}" optionKey="id" optionValue="name" />');

The problem with this code is that when the g:select tag expands, it will generate the code as follows:

    $('#worker').html('<select onchange="handleWorkerChange(this)" class="dropdown" name="worker" id="worker" >
<option value="2" >Worker1</option>
<option value="4" >Worker1</option>
<option value="18" >Worker1</option>
<option value="19" >Worker1</option>
</select>');

As you can see above, when expanding, the option tags are in new lines so this will cause syntax error in JavaScript. Is there a way so that the select gsp tag will expand to a single line string so that the select box can be embedded dynamically in a div?


Solution

  • g:select is also available just as a method within the GSP:

    ${select(from:aList,value:aValue)}
    

    Taking advantage of this and the fact that then we are just dealing with a text (org.codehaus.groovy.grails.web.util.StreamCharBuffer), we can remove the new line characters:

    $('#worker').html('${ select(
        class: 'dropdown', 
        from: workers, 
        optionKey='id', 
        optionValue: 'name', 
        name: 'worker'
    ).replace(System.getProperty("line.separator"), '') }');
    

    This should result in the entire select be placed on a single line.


    Initially, I wasn't sure myself exactly what was causing the select being placed over several lines, so I went straight to the source: FormTagLib.

    Snippet from FormTagLib:

    writer << "<select "
    // process remaining attributes
    outputAttributes(attrs, writer, true)
    
    writer << '>'
    writer.println()
    

    As you can see, it's just a simple println method call:

    Terminates the current line by writing the line separator string. The line separator string is defined by the system property line.separator, and is not necessarily a single newline character ('\n').

    This is why it's important to use System.getProperty("line.separator").