Use Builder templates in Grape!
This gem is completely based on grape-jbuilder which in turn is completely based on grape-rabl.
Add this line to your application's Gemfile:
gem 'grape-builder' 
And then execute:
$ bundle
# config.ru
require 'grape/jbuilder'# config.ru
require 'grape/builder'
use Rack::Config do |env|
  env['api.tilt.root'] = '/path/to/view/root/directory'
endclass API < Grape::API
  format :xml
  formatter :xml, Grape::Formatter::Builder
endAdd the template name to the API options.
get '/user/:id', builder: 'user.builder' do
  @user = User.find(params[:id])
endYou can use instance variables in the builder template.
xml.user do
  xml.name(@user.name)
  xml.email(@user.email)j
  xml.project do
    xml.name(@project.name)
  end
endget ':id' do
  user = User.find_by(id: params[:id])
  if article
    env['api.tilt.template'] = 'users/show'
    env['api.tilt.locals']   = {user: user}
  else
    status 404
    {'status' => 'Not Found', 'errors' => "User id '#{params[:id]}' is not found."}
  end
endThe following are identical.
get '/home', builder: 'view'
get '/home', builder: 'view.jbuilder'# config.ru
require 'grape/builder'
use Rack::Config do |env|
  env['api.tilt.root'] = '/path/to/view/root/directory'
end
class UserAPI < Grape::API
  format :xml
  formatter :xml, Grape::Formatter::Builder
  # use Builder with 'user.builder' template
  get '/user/:id', builder: 'user' do
    @user = User.find(params[:id])
  end
  # do not use builder, fallback to the defalt Grape XML formatter
  get '/users' do
    User.all
  end
end# user.builder
xml.user do
  xmlname(@user.name)
endCreate a grape application.
# app/api/user.rb
class MyAPI < Grape::API
  format :xml
  formatter :xml, Grape::Formatter::Builder
  get '/user/:id', builder: 'user' do
    @user = User.find(params[:id])
  end
end# app/views/api/user.builder
xml.user do
  xml.name(@user.name)
endEdit your config/application.rb and add view path
# application.rb
class Application < Rails::Application
  config.middleware.use(Rack::Config) do |env|
    env['api.tilt.root'] = Rails.root.join 'app', 'views', 'api'
  end
endMount application to Rails router
# routes.rb
GrapeExampleRails::Application.routes.draw do
  mount MyAPI , at: '/api'
endUse the partial.render method to render a partial template
# app/views/api/user/index.builder
xml.users do
 @users.each do |u|
    xml << partial.render('user/show', user: u)
 end
end# app/views/api/user/show.builder
xml.user do
  xml.name(@user.name)
endSee "Writing Tests" in https://github.com/intridea/grape.
Enjoy :)
Special thanks to @milkcocoa because this gem is completely based on grape-jbuilder.
Also thanks to @LTe since grape-jbuilder is based on grape-rabl.
- Fork it
- Create your feature branch (git checkout -b my-new-feature)
- Commit your changes (git commit -am 'Add some feature')
- Push to the branch (git push origin my-new-feature)
- Create new Pull Request