ruby-on-rails - 如何在 Controller 中呈现 View 并分配给变量 (Rails)

标签 ruby-on-rails ruby ruby-on-rails-5

我有以下 View 代码:

app/views/calendars/try.html.erb

<%= @ow %>

然后在我的 Controller 中,我有以下内容:

app/controllers/calendars_controller.rb

class CalendarsController < ApplicationController
  def try
    @ow = 'hello'
  end
end

问题是,我想获取 View 文件的内容并将其分配给 Controller 中的一个变量。

类似于 myvar = content_of_my_view然后 myvar将返回 hello .

这样可以吗?

我尝试了以下方法:

测试 1:

class CalendarsController < ApplicationController
  def try
    @ow = 'hello'

    html = open(Rails.root.join('app','views','calendars','try.html.erb')).read

    raise html.inspect
  end
end

这将返回 <%= @ow %>作为纯文本不是 hello只是我想要的。

测试 2:

class CalendarsController < ApplicationController
  def try
    @ow = 'hello'

    html = open(File.join('app','views','calendars','try.html.erb')).read

    raise html.inspect
  end
end

测试 1 中的相同输出。

测试 3:

class CalendarsController < ApplicationController
  def try
    @ow = 'hello'

    html = open(Rails.root.join('app','views','calendars','try.html.erb'), 'rb') {|io| a = a + io.read}

    raise html.inspect
  end
end

测试 1测试 2 的输出相同。

测试 4:

class CalendarsController < ApplicationController
  def try
    @ow = 'hello'

     html = IO.binread(Rails.root.join('app','views','calendars','try.html.erb'))

    raise html.inspect
  end
end

测试 1测试 2测试 3 中的输出相同。

测试 5:

class CalendarsController < ApplicationController
  def try
    @ow = 'hello'

     html = render('o')

    raise html.inspect
  end
end

这不会返回任何内容。

是否可以将其返回为 hello从 Controller ?我似乎找不到一种方法来呈现变量而不是将其打印为纯文本。

最佳答案

您可以使用 render_to_string呈现 ERB 模板并将其内容作为字符串返回。

关于ruby-on-rails - 如何在 Controller 中呈现 View 并分配给变量 (Rails),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51434283/

相关文章:

javascript - Time.now 在部分 rails 上没有改变

ruby-on-rails - Rails 5 - 在 link_to 中,如何传递 nil (NULL) 参数?

ruby-on-rails - 为什么 Rails 应用程序显示/公共(public)索引列表而不是实际应用程序?

ruby-on-rails - 如何在 Rails 应用程序中实现 TCP 套接字?

ruby - 在 ruby​​ 的网页中查找重复模式

ruby - 为什么 ruby​​ 只返回正则表达式的最后一个匹配项?

ruby-on-rails - 如何为 ios 设置 "build Turbolinks.framework"?

ruby-on-rails - 每个 Rails 项目都必须有 ruby gem (2011 版)

ruby-on-rails - rails : Whats the easiest method to convert a serialized hash column into json column

ruby-on-rails - 在 Rails 中,如何删除数组中的所有对象?