3

I have a requirement where I need to generate/spit out HTML markup from one of my APIs. I am using grape API but cannot find a way to throw out HTML markup. I can specify content-type as text/html and create a HTML markup but is there a better way to achieve this like rendering a template similar to below:

render template:'my_template' locals: {:data => data}  

and 'my_template' (HTML) can take care of how the page looks like ? render is an undefined method in GrapeAPI so not sure what other stuff I can use ?

wpp
  • 7,093
  • 4
  • 33
  • 65
Kush
  • 909
  • 1
  • 8
  • 14

1 Answers1

2

I think it's quite a bad idea to use an API only framework to render HTML...

Nevertheless, you should be able to use the :txt content-type to simply render out your string like you described.

You could use ERB for that, as it is part of the standard-library and pretty easy to use:

require "erb"

class Template
  attr_reader :name, :data

  def initialize(name, data)
    @name = name
    @data = data
  end

  def build
    raw = File.read("templates/#{name}.erb")
    ERB.new(raw).result(binding)
  end
end

as far as I read, grape automatically uses the to_s method of an entity to render :txt, so you could implement something like this in your model:

def to_s
  Template.new(self.class.to_s.downcase, self)
end

it might also be possible to register a html content type and write some kind of formatter that does this kind of stuff.

phoet
  • 18,688
  • 4
  • 46
  • 74