Add the grape and grape-erb gems to Gemfile.
gem 'grape'
gem 'grape-erb'And then execute:
$ bundle
# config.ru
use Rack::Config do |env|
env['api.tilt.root'] = '/path/to/view/root/directory'
endclass API < Grape::API
content_type :json, 'application/json'
content_type :html, 'text/html'
formatter :html, Grape::Formatter::Erb
format :html
endAdd the template name to the API options.
get "/user/:id", erb: "users/show" do
@user = User.find(params[:id])
endYou can use instance variables in the Erb template.
<% unless @user.nil? %>
<h2><%= @user.name %></h2>
<p><%= @user.bio %></p>
<% end %>Gape-erb first looks for a layout file in #{env['api.tilt.root']}/layouts/application.html.erb.
You can override the default layout conventions:
# config.ru
use Rack::Config do |env|
env['api.tilt.root'] = '/path/to/view/root/directory'
env['api.tilt.layout'] = 'layouts/another'
endThe following are identical.
get "/home", erb: "view"
get "/home", erb: "view.html.erb"Create grape application
# app/api/user.rb
class MyAPI < Grape::API
content_type :json, 'application/json'
content_type :js, 'text/javascript'
content_type :html, 'text/html'
formatter :html, Grape::Formatter::Erb
formatter :js, Grape::Formatter::Erb
format :json # Default format
get '/user/:id' do
env['api.format'] = :html
content_type 'text/html'
@user = User.find(params[:id])
render erb: 'users/show'
end
end# app/views/api/user.html.erb
<% unless @user.nil? %>
<h2><%= @user.name %></h2>
<p><%= @user.bio %></p>
<% end %>Edit 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
endSee "Writing Tests" in https://github.com/intridea/grape README.
Enjoy :)
- Fork it
- Create your feature branch (
git checkout -b my-new-feature) - Commit your changes (
git commit -am 'Added some feature') - Push to the branch (
git push origin my-new-feature) - Create new Pull Request