Skip to content
A example code for implementing layout for xml response.
Ruby JavaScript
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
app
config
db
doc
lib/tasks
public
script
test
vendor/plugins
.gitignore
.rvmrc
Gemfile
Gemfile.lock
README.md
Rakefile
config.ru

README.md

CeXmlLayout

What's This?

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.

Why can't I just create app/views/layouts/application.xml.builder?

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!

So how to solve?

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.

Any quick fixes?

Ya, you could do:

# application.xml.builder
xml.instruct!

xml.root do
  xml << yield.gsub(/^/, "  ")
end

Any better fixes?

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!

Files I should read in the example

  • app/views/layout/application.xml.builder
  • app/views/songs/index.xml.builder
  • app/controllers/songs_controller.rb
You can’t perform that action at this time.