How could I render to a string a JSON representation of a JBuilder view?

后端 未结 8 1457
抹茶落季
抹茶落季 2020-12-29 05:18

I\'m using JBuilder as to return some JSON. I have a index.json.jbuilder that generates the data, and I need to render it to a string. However, I\'m not sure ho

相关标签:
8条回答
  • 2020-12-29 05:28

    From console:

    view = ApplicationController.view_context_class.new("#{Rails.root}/app/views")
    JbuilderTemplate.encode(view){|json| json.partial!('path/to/index', @my_object) }
    

    via https://github.com/rails/jbuilder/issues/84#issuecomment-38109709

    0 讨论(0)
  • 2020-12-29 05:30

    If the view users.json.jbuilder is at the default path relative to the controller and it cannot find the template, it may be due to a format discrepancy, as it may be trying to look for the html format file. There are two ways to fix this:

    1. Have the client GET /users/index.json

      or

    2. Specify the formats option when calling render_to_string (also applies to render):


    #controllers/users_controller.rb
    def index
      @users = User.all
      @users_json = render_to_string( formats: 'json' ) # Yes formats is plural
    end
    

    This has been verified in Rails 4.1.

    0 讨论(0)
  • 2020-12-29 05:31

    Looking at the source code, it looks like you can do:

    json_string = Jbuilder.encode do |json|
      json.partial! 'path/to/index', @my_object
    end
    
    0 讨论(0)
  • 2020-12-29 05:42

    in controller you can do like this

    def index
      json = JbuilderTemplate.new(view_context) do |json|
        json.partial! 'index'
      end.attributes!
      do_something(json)
      render json: json
    end
    

    note that you need "_index.json.jbuilder" because it calls partial renderer

    0 讨论(0)
  • 2020-12-29 05:46

    I am rendering a collection of users as a json string in the controller like so:

    #controllers/users_controller.rb
    def index
      @users = User.all
      @users_json = render_to_string( template: 'users.json.jbuilder', locals: { users: @users})
    end
    
    #views/users/users.json.jbuilder
    json.array!(users) do |json, user|
      json.(user, :id, :name)
    end
    
    0 讨论(0)
  • 2020-12-29 05:49

    Following justingordon's tip.

    If you are using a React component, you can do the following.

    In your controller:

    @users = User.all
    

    In your view:

    <%= react_component("YourComponentName",
                        props: render('your_template.json.jbuilder')) %>
    

    This was tested on Rails 5.1.

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