Task G: One Last Wafer Thin Change #2

It would be interesting to read some opinions here…

We have to change some code. In order to prevent the framework to embed the xml output in the layout html code of store.rhtml, we have to add some options in a block after format.xml {…} in 'store_controller.rb'

# ...
def index
  @time = Time.now
  @products = Product.find_products_for_sale
  @count = increment_count
  respond_to do |format|
    format.html
    # change here
    format.xml {render :template=>'store/index.rxml', :layout=>false}
  end
end
# ...

After that, create an 'index.rhtml' file in /app/views/store with the following content:

xml.instruct!
xml.declare! :DOCTYPE, :html, :PUBLIC, "-//W3C//DTD XHTML 1.0 Strict//EN",     
                    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"
# => <!ELEMENT blah "yada">
xml.html("xmlns" => "http://www.w3.org/1999/xhtml") do
  xml.head do
    xml.title("Products")
  end
  xml.body do
    for product in @products
      xml.p do
        xml.h1(product.title)
        xml.p(product.description)
        xml.p(product.image_url)
      end
    end
  end
end

Now, you should get all products as XHTML in your browser after calling http://localhost:3000/store/index.xml

Gustavo:

It didn't work for me. Rails seems to be rendering index.rhtml as an RHTML template, cause when I browse the page instead of seeing the code generated by the RXML template, I just see the code for it.

Ronnie:

The 'index.rhtml' file should be renamed to either 'index.rxml' or 'index.xml.builder' and it should work correctly.

Store controller code can just be:

# ...
def index
  @time = Time.now
  @products = Product.find_products_for_sale
  @count = increment_count
  respond_to do |format|
    format.html
    format.xml {render :layout=>false}
  end
end
# ...
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License