I'm having an issue with my index.xml.builder file for picture albums; I'm sure it's something simple but it's driving me crazy after not finding a solution in the Builder::XmlMarkup docs. Here is my current view:
xml.instruct!
xml.gallery {
@albums.each { |g|
xml.album(g.name, {:title => g.name,
:description => g.description,
:lgpath => "[PATH]",
:tnpath => "[PATH]",
:fspath => "[PATH]"})
g.pictures.each { |p|
xml.img nil, :src => "#{p.resource_file_name}"
}
}
}
However, this is producing the following:
<gallery>
<album title="..." description="..." lgpath="..." tnpath="..." fspath="..."></album>
<img src="17112.jpg"/>
<img src="17113.jpg"/>
<img src="17114.jpg"/>
<img src="17115.jpg"/>
<album...
As you can see, I am unable to get the images nested inside the </album>
tag. Any ideas how to get that going?
Thanks in advance.
WRAP-UP (Thanks to iain for putting me on the right path):
Never underestimate reading the source code, in this case Builder::XmlBase#method_missing. The solution was to not pass in a string for the tag content (g.name). This is the code that I needed:
xml.instruct!
开发者_Python百科xml.gallery do
@albums.each do |g|
xml.album(:title => g.name) do
g.pictures.each do |p|
xml.img(:src => p.resource_file_name)
end
end
end
end
Look again, because Builder doesn't generate invalid XML.
After stubbing out some things (replacing the gallery and pictures with simple arrays), you essentially wrote this code:
xml.instruct!
xml.gallery do
[1, 2, 3].each do |g|
xml.album g.to_s, :title => g.to_s, :fspath => "[PATH]"
[4, 5, 6].each do |p|
xml.img nil, :src => "#{p}.gif"
end
end
end
Which results in this XML:
<?xml version="1.0" encoding="UTF-8"?>
<gallery>
<album title="1" fspath="[PATH]">1</album>
<img src="4.gif"></img>
<img src="5.gif"></img>
<img src="6.gif"></img>
<album title="2" fspath="[PATH]">2</album>
<img src="4.gif"></img>
<img src="5.gif"></img>
<img src="6.gif"></img>
<album title="3" fspath="[PATH]">3</album>
<img src="4.gif"></img>
<img src="5.gif"></img>
<img src="6.gif"></img>
</gallery>
You probably want to have the img-tags inside the album tags, but your own nesting is wrong for that. Indenting your code will help you figure it out, and using do
...end
blocks instead of curly braces, whenever you use multiple lined blocks helps the structure too.
精彩评论