-
-
Notifications
You must be signed in to change notification settings - Fork 184
Usage with jbuilder
Phil Chen edited this page Nov 7, 2017
·
10 revisions
Use gon with Jbuilder templates. It's similar in use to the Rabl integration:
- Add Jbuilder to the Gemfile before requiring gon, as gon checks the Jbuilder constant.
Gemfile
gem 'jbuilder'
# ...
gem 'gon'
- Create Jbuilder template.
app/views/posts/index.json.jbuilder
json.posts @posts, :id, :title, :body
- In your controller you should just call 'gon.jbuilder' - if your template is in
the default directory for the action. In the other cases - you still can use
:template
option to thejbuilder
method.
With default template location
def index
# some controller logic
@posts = Post.all
gon.jbuilder
# some controller logic
end
With custom template location
def index
# some controller logic
@posts = Post.all
gon.jbuilder template: 'app/views/posts/myposts.json.jbuilder', as: :my_posts
# some controller logic
end
In javascript file for view of this action write call to your variable:
Now you can use partials in jbuilder:
app/views/posts/index.json.jbuilder
json.partial! 'posts/part', :comments => @posts[0].comments
app/views/posts/_part.json.jbuilder
json.comments comments.map{ |it| 'comment#' + it.id }
alert(gon.posts)
alert(gon.posts[0])
alert(gon.posts[0].post.body)
alert(gon.comments)
alert(gon.comments[0])
P.S. If you didn't put include_gon tag in your html head area - it wouldn't work. You can read about this in common usage above.