json erb template cannot find other html partial

前端 未结 4 1224
Happy的楠姐
Happy的楠姐 2021-01-02 06:41

I am trying to have a json response in which some value is html rendered by a partial

#projects_Controller.rb

def index
  respond_to do |f|
    f.json 
  en         


        
相关标签:
4条回答
  • 2021-01-02 07:01

    Got it: All one needs is this line in the .json.erb file <% self.formats = ["html"] %>

    So the full index.json.erb

          <% self.formats = ["html"] %>
          disclaimer = {
            "html":"<%= raw escape_javascript(render :partial => 'projects/disclaimer',
                        :content_type => 'text/html'), 
                        :locals => {:localVariable => @localVariable} 
                    %>"
          }
    
    0 讨论(0)
  • 2021-01-02 07:04

    My answer is similar to Nik's above. I have the following helper for json.erb templates:

    # 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
    

    So now I can write templates like

    {
      "html": <%=json render_html(:partial => 'some_partial') %>,
      "status": success
    }
    

    This would be nicer if actionview allowed rendering with a content_type like in 23tux's example (which doesn't work for me). It would also be nicer if only *.html.erb underwent html escaping instead of all *.erb files.

    0 讨论(0)
  • 2021-01-02 07:11

    For future readers, you may pass on formats parameter like this.

    = render partial: 'user', locals: {xyz: @xyz}, :formats => [:html]
    
    0 讨论(0)
  • 2021-01-02 07:14

    I'm not sure if I got you right, but maybe you can play with the content type like this:

    disclaimer = {
      "html":"<%= raw escape_javascript(render :partial => 'projects/disclaimer', :content_type => 'text/html'), :locals => {:localVariable => @localVariable} %>"
    }
    

    The :locals is just if you want to pass an var to the partial.

    0 讨论(0)
提交回复
热议问题