Rails format.xml 渲染并传递多个变量

发布于 2024-11-01 02:22:55 字数 463 浏览 3 评论 0原文

典型用法是:

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

现在我还想传递一个名为“teststring”的字符串。

参考

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

我已经看到了使用但我不知道如何将两者合并在一起的 。我只是还没有看到所有的东西。没有太多文档来真正解释该行中的 :xml 。我不知道是否可以用 :teststring => 处理字符串测试字符串?

最后,既然我有多个变量,我该如何在 index.html.erb 中处理它们?它们是否从渲染命令中以相同的名称传递?

谢谢。

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 haven'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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

莳間冲淡了誓言ζ 2024-11-08 02:22:55

如果要呈现自定义 XML,则需要在控制器的相应视图目录中创建一个 index.xml.erb 文件。它的工作方式就像您使用的任何 HTML 模板一样,然后:

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>

(您可以在此处阅读有关 ActiveRecord 的 to_xml 方法< /a>。)

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.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文