logo       

Re: MarkupBuilder combining attributes and content: msg#00156

lang.groovy.user

Subject: Re: MarkupBuilder combining attributes and content

Hi,

I have tried to fix this problem with just a few lines of code change. I am attaching a patchfile with the changes. It's not the most elegant solution, perhaps, but the case statements in that code have painted the XML builder into corners that would take more brain power to undo than I could apply to it tonight.

Attachment: MarkupBuilder.patchfile.txt
Description: Text document



With the following groovy code it outputs the following HTML:
import groovy.xml.MarkupBuilder;

xhtml = new MarkupBuilder()

html = xhtml.html() {
head {
title('My Title')
}
body(bgcolor:"#FFFFFF") {
p {
a(href:"http://groovy.codehaus.org";, "Groovy")
a(href:"http://groovy.codehaus.org";, "\"Groovy\"")
}
table {
tr {
td(class:"special", "cell value")
td(class:"special2", "another cell value")
}
}
}
}
println html

HTML ouput:
<html>
<head>
<title>My Title</title>
</head>
<body bgcolor='#FFFFFF'>
<p>
<a href='http://groovy.codehaus.org'>Groovy</a>
<a href='http://groovy.codehaus.org'>"Groovy"</a>
</p>
<table>
<tr>
<td class='special'>cell value</td>
<td class='special2'>another cell value</td>
</tr>
</table>
</body>
</html>

Hope this helps,
Scott Stirling
Framingham, MA

On Nov 22, 2004, at 1:28 PM, Guillaume Laforge wrote:

Ken Pelletier wrote:
How can I use MarkupBuilder to generate html elements that have both attributes and content?
I can't seem to locate any examples anywhere, but it's such an essential case I'm sure it's supported.
Eg: <td class="foo">some content here</td>
mb = new MarkupBuilder()
mb.td(class:"foo") // yields <td class='foo' />
mb.td("some content here") // yields <td>some content here</td>
mb.td(class:"foo", "some content here") // yields <td class='foo' />
I believe there was an example on the wiki here http://wiki.codehaus.org/groovy/TreeBasedSyntax but that page seems to have disappeared today - at least it's been inaccessible to me since this afternoon.

Though that's a very common use case, unfortunately, MarkupBuilder is quite limited and cannot generate such simple tags.
You'll have to use StreamingMarkupBuilder which you can build from Groovy sources (since in the last build, due to a build problem, this class hasn't been included in the distribution).
To know how it works, you should have a look at DocGenerator.groovy in the source distribution, there are some good examples of its usage.

--
Guillaume Laforge
http://glaforge.free.fr/weblog

<Prev in Thread] Current Thread [Next in Thread>
Google Custom Search

News | FAQ | advertise