How could I render to a string a JSON representati

2020-02-23 06:28发布

问题:

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 how to do this, since: @my_object.to_json and @my_object.as_json don't seem to go through JBuilder.

How could I render the JBuilder view as a string?

回答1:

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


回答2:

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.



回答3:

You can also do it like this, which leaves your controller a bit cleaner.

# controller
def new
  @data = Data.all
end


# view
<% content_for :head do %>
  <script type="text/javascript">
    var mydata = <%= raw render :partial => 'path/to/partial', :locals => {data: @data} %>;
  </script>
<% end %>


# path/to/_partial.html.jbuilder
json.array!(@data) do |d|
  json.extract! field1, :field2, :field3, :field4
  json.url data_url(d, format: :json)
end


# layouts/application.html
<!DOCTYPE html>
<html>
<head>
  <%= yield :head %>
</head>
<body>
...
</body>
</html>


回答4:

If you're doing this in the controller, a much simpler option is to try to the move the code into the view being rendered by the controller.

I described this here: https://github.com/shakacode/react-webpack-rails-tutorial/blob/master/docs/jbuilder.md

basically you can call render in the view, and you're done. Like this:

<%= react_component('App', render(template: "/comments/index.json.jbuilder"),
    generator_function: true, prerender: true) %>

Here's the notes on what happens if you want to pass the data from the controller to the view:

class PagesController < ApplicationController
  def index
    @comments = Comment.all

    # NOTE: The below notes apply if you want to set the value of the props in the controller, as
    # compared to he view. However, it's more convenient to use Jbuilder from the view. See
    # app/views/pages/index.html.erb:20
    #
    #  <%= react_component('App', render(template: "/comments/index.json.jbuilder"),
    #     generator_function: true, prerender: true) %>
    #
    #
    # NOTE: this could be an alternate syntax if you wanted to pass comments as a variable to a partial
    # @comments_json_sting = render_to_string(partial: "/comments/comments.json.jbuilder",
    #                                         locals: { comments: Comment.all }, format: :json)
    # NOTE: @comments is used by the render_to_string call
    # @comments_json_string = render_to_string("/comments/index.json.jbuilder")
    # NOTE: It's CRITICAL to call respond_to after calling render_to_string, or else Rails will
    # not render the HTML version of the index page properly. (not a problem if you do this in the view)
    # respond_to do |format|
    #   format.html
    # end
  end
end


回答5:

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


回答6:

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



回答7:

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



回答8:

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.