json erb模板找不到其他html偏

Nik*_* So 10 json ruby-on-rails partial-views

我正在尝试使用json响应,其中某些值是由部分呈现的html

#projects_Controller.rb

def index
  respond_to do |f|
    f.json 
  end
end

# index.json.erb

  {
     "html":"<%= raw escape_javascript(render :partial => 'projects/disclaimer') %>"
  }
Run Code Online (Sandbox Code Playgroud)

但是我收到以下错误:

  ActionView::Template::Error (Missing partial projects/disclaimer with {:handlers=>[:erb, :rjs, :builder, :rhtml, :rxml], :formats=>
  [:json], :locale=>[:en, :en]} in view paths "c:/rails/app/views", "c:/rails/vendor/plugins/more/app/views", "C:/Ruby192/lib/ruby/gems/1.9.1/gems/devise-1.1.8/app/views")
Run Code Online (Sandbox Code Playgroud)

似乎JSON请求在其名称中使用.json.erb呈现部分但不是.html.erb,这就是我所拥有的.有没有办法让我指定'html'.

ADDED:如果请求是'js',并且在index.js.erb中我渲染了几乎相同的代码:#index.js.erb

  disclaimer = {
     "html":"<%= raw escape_javascript(render :partial => 'projects/disclaimer') %>"
  }
Run Code Online (Sandbox Code Playgroud)

它确实找到了projects/disclaimer.html.erb并正确呈现它.我想知道为什么会出现这样的不一致,如果有人请求js,其模板中的任何部分渲染都会查找partial_name.html.erb但是如果请求json,部分渲染会要求partial_name.json.erb?

谢谢

Nik*_* So 13

得到它:所有需要的是.json.erb文件中的这一行<%self.formats = ["html"]%>

所以完整的index.json.erb

      <% self.formats = ["html"] %>
      disclaimer = {
        "html":"<%= raw escape_javascript(render :partial => 'projects/disclaimer',
                    :content_type => 'text/html'), 
                    :locals => {:localVariable => @localVariable} 
                %>"
      }
Run Code Online (Sandbox Code Playgroud)

  • 这种方法也适用于渲染JSON的控制器内部; 我设置`self.formats = [:html]`,然后`render_to_string(:partial =>'an_html_partial',:locals => {:whatever => whatever})`,然后我可以渲染json. (5认同)

小智 5

我的回答类似于上面的Nik.我为json.erb模板提供了以下帮助:

# helpers useful for json.erb templates
module JsonHelper

  # Same as render but force actionview to look for html templates instead of json.
  def render_html(options={}, locals={}, &block)
    old_formats = formats
    self.formats = [:html] # hack so partials resolve with html not json format
    render options, locals, &block  

  ensure
    self.formats = old_formats 
  end 

  # json escape a string. For example <%=json "some { string }" %>
  def json(value)
    raw value.to_json
  end 
end
Run Code Online (Sandbox Code Playgroud)

所以现在我可以编写类似的模板

{
  "html": <%=json render_html(:partial => 'some_partial') %>,
  "status": success
}
Run Code Online (Sandbox Code Playgroud)

如果actionview允许使用类似于23tux的示例中的content_type进行渲染(这对我不起作用),这将更好.如果只有*.html.erb进行html转义而不是所有*.erb文件,那也会更好.