Non-tech founder’s guide to choosing the right software development partner Download Ebook
Home>Blog>How to conditionally render template in grape resources?

How to conditionally render template in Grape resources?

Suppose you need to conditionally render some template in a given endpoint of a Grape resource. There is a env data in Grape::API class that represents Rack environment of the request. env is just a simple Ruby hash and we can pass the template name to it's api.tilt.template key to render that template:


env['api.tilt.template'] = 'foo/bar.json'

Then let's define a render method in Base resourсe:


class Base < Grape::API

  def self.inherited(subclass)

    super



    subclass.instance_eval do

      helpers do

        def render(template_name)

          env['api.tilt.template'] = template_name

        end

      end

    end

  end

end

Now we can use it in the following way:


class ContactsResource < Base

  desc 'Create contact', http_codes: [[201, 'Created']]



  post '/contacts' do

    contact = Contact.new(params[:contact])



    if contact.save

      render 'v1/contacts/show.json'

    else

      error!({ errors: contact.errors.full_messages }, 422)

    end

  end

end

Discover More Reads

Categories:

Recent Projects

We take pride in creating applications that drive growth and evolution, from niche startups to international companies.

Let’s Build Something Great Together

Let’s discuss your project and see how Ruby on Rails can be your competitive advantage.

*By submitting this form, you agree with JetRockets’ Privacy Policy