This is an example code in the "Ce" series. The example code is to demonstrate how to apply layout to the xml response generated by using xml builder.
With the help of using a layout file for the xml builder, it would be suitable to generate common outermost elements, which would suit the case for generating RSS, ATOM, or other responses with some common elements.
Yes you can. However the problem is when you use yield
, you will find that the yield
actually produces nothing!
Why?
In xml.builder
files, you output response by using xml
, such as xml.instruct!
. Each builder simply creates different xml
. If you run xml.songs
in both app/views/layout/application.xml.builder
and app/views/songs/index.xml.builder
, the two xml
are different objects!
To resolve the problem, thanks to @Kris Martin in answering my question on StackOverflow (http://stackoverflow.com/questions/6568450/layout-for-xml-builder-in-rails-3), I know that we could do something like:
xml << yield
It works perfectly, except the yielded content indented incorrectly.
Ya, you could do:
# application.xml.builder
xml.instruct!
xml.root do
xml << yield.gsub(/^/, " ")
end
I can't find yet. If any of you have ideas on this, please leave me comments / issues.
Forking and doing a pull request are welcome!
- app/views/layout/application.xml.builder
- app/views/songs/index.xml.builder
- app/controllers/songs_controller.rb