Note that there are some explanatory texts on larger screens.

plurals
  1. PORails JSON API layouts with Jbuilder (or other)
    text
    copied!<p>In my rails 3.2 app, I'm using <a href="https://github.com/rails/jbuilder">jbuilder</a> to render responses from my JSON api.</p> <p>I want to provide a common structure to all API responses, and a layout would be the likely solution to keep my views DRY.</p> <p>ex: I'd like every response to be of the following form :</p> <pre><code>{ status: "ok|error|redirect", data: { ... JSON specific to the current view ... }, errors: [ ... ], notes: [ ... ] } </code></pre> <p>(where the value for <strong>data</strong> is a json structure provided by the view, everything else is from the layout)</p> <p>However: I can't get the jbuilder layout yielding to the view correctly.</p> <pre><code># in layout json.data yield # in view json.some "value" </code></pre> <p>results in:</p> <pre><code>{"data":"{\"some\":\"value\"}"} # arg! my json has become a string </code></pre> <p>Trying things another way:</p> <pre><code># in layout yield # in view json.data do |json| json.some "value" end </code></pre> <p>results in :</p> <pre><code>{} </code></pre> <p>Has anyone had success doing this with jbuilder, or another json templating gem/method?</p> <p>This <a href="https://github.com/rails/jbuilder/issues/8">juilder github issue</a> suggests it's possible, but indicates others are having similar issues.</p> <p>I see rabl (https://github.com/nesquena/rabl/) is supposed to support layouts (https://github.com/nesquena/rabl/wiki/Using-Layouts), but I've decided not to use it for other reasons (rabl makes complex json structures a nightmare, particularly when trying to control object roots etc).</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload