开发者

Rails format.xml render and pass multiple variables

开发者 https://www.devze.com 2023-02-23 05:12 出处:网络
Typical usage is: respond_to do |format| format.html # index.html.erb format.xml{ render :xml => @users }

Typical usage is:

respond_to do |format|
  format.html # index.html.erb
  format.xml  { render :xml => @users }
end

And now I want to also pass a string named "teststring".

I've seen reference to using

:local => {:users => @users, :another => @another}

But I don't know how to merge the two together. I just hav开发者_JS百科en't seen everything all together. Not much documentation to really explain the :xml in that line. And I don't know if I can deal with the string with :teststring => teststring?

And lastly, how do I deal with them in my index.html.erb now that I have multiple variables? Do they get passed with the same name from the render command?

Thanks.


If you want to render custom XML, you'll need to create a index.xml.erb file in the corresponding view directory for the controller. It works just like any HTML template you'd use, then:

app/controllers/home_controller.rb:

def index
    @users = ...
    @another = "Hello world!"

    # this `respond_to` block isn't necessary in this case -
    # Rails will detect the index.xml.erb file and render it
    # automatically for requests for XML
    respond_to do |format|
        format.html # index.html.erb
        format.xml # index.xml.erb
    end
end

app/views/home/index.xml.erb:

<?xml version="1.0" encoding="UTF-8"?>
<document>
    <%= @users.to_xml # serialize the @users variable %>
    <extra_string><%= @another %></extra_string>
</document>

(You can read about ActiveRecord's to_xml method here.)

0

精彩评论

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

关注公众号