Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Groovy XML MarkupBuilder to create valid HTML script tags?

I am using Groovy 1.8 XML MarkupBuilder to build an HTML page which includes a <script> tag.

When I load the page in Firefox 18 I see a blank page instead of the expected results.

This seems to be due to the generated <script> tag not having a complementary </script> tag, even though there is no content to warrant the </script> tag. (See: https://stackoverflow.com/questions/69913/why-dont-self-closing-script-tags-work )

Sample Groovy code:

def builder = new groovy.xml.MarkupBuilder( out )

builder.html {
  head {
    script( type:'text/javascript', src:'//example.com/example.js' )
  }

  body {
    p("Hello...Newman.")
  }
}

If I examine the (blank) rendered page's HTML using Firefox's "View Page Source" (Ctrl-U), I see:

<html>
  <head>
    <script type='text/javascript' src='//example.com/example.js />
  </head>
  <body>
    <p>Hello...Newman.</p>
  </body>
</html>

Looking closely, I see the '/' on the <script ... /> tag is rendered in red, and the hover-over text on the '/' says "Self-closing syntax ("/>") used on a non-void HTML element. Ignoring the slash and treating as a start tag."

So, how do I generate valid HTML <script> tags using Groovy XML MarkupBuilder ?

like image 893
m0j0hn Avatar asked Feb 13 '13 19:02

m0j0hn


2 Answers

If you define some empty content, then the script tag will have a separate closing tag:

script( '', type:'text/javascript', src:'//example.com/example.js' )
like image 58
tim_yates Avatar answered Nov 15 '22 10:11

tim_yates


Alternatively you could use

script(type:'text/javascript', src:'//example.com/example.js){mkp.yield("")}

like image 35
zmanc Avatar answered Nov 15 '22 09:11

zmanc