开发者

How do I render a .builder template in ruby on rails?

I am really confused about how to utilize builder templates in ruby on rails. I have some simple controller code:

class ProductsController < ApplicationController

  def index
    @products = Product.all
    respond_to do |format|
      format.html # index.html.erb
      format.xml  # index.builder
    end
  end

end

but this does not seem to work. My index.builder file looks like this:

xm = Builder::XmlMarkup.new(:target=>$stdout, :indent=>2)
xm.instruct!          
  xm.i开发者_C百科ndex{
    @index.each do |i|
      xm.country(i.country.name)
      xm.value(i.value)
      xm.year(i.year)
    end
  }

but I keep getting a blank response. Looks like I am not understanding something fundamental here.


Rename index.builder to index.xml.builder and then the xml object is already available in index.builder, so you can tweak your builder file to look like this:

xml.instruct!
xml.posts do
  @products.each do |product|
    xml.product do
      xml.title product.title
      xml.body product.body
      xml.price product.price
    end
  end
end

More here: http://danengle.us/2009/05/generating-custom-xml-for-your-rails-app/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜