我有以下 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/