-
Notifications
You must be signed in to change notification settings - Fork 335
Using Layouts
It may be desirable to use a common layout file for all JSON responses - to include a response code or other metadata. For example, the Google Geocoder API returns a 'status' field, and all response data under 'results'.
When returning JSON data, the rails application will merge controller output with a layout file via 'yield', just as can be done with view layout files. Below is an example json layout file:
<% # app/views/layouts/application.json.erb %>
{
"metadata": <%= @metadata.to_json.html_safe %>,
"error": <%= @error.to_json.html_safe %>,
"result": <%= yield %>
}
In this case, the rendered output of your .rabl
will appear under the 'result' field (or wherever the yield is placed in the layout file). The controller can pass metadata and error values via instance variables.
Note the html_safe
- this prevents rails from auto-escaping the JSON output. The raw
helper can also be used. This blog post explains the difference.