Nigel Thorne
Nigel Thorne

Reputation: 21548

Can you stream HTML with Slim in a Sinatra app?

I have a Sinatra app that wraps a command line application. It doesn't have may users, so performance is not a problem.

I am using Sinatra's streaming api to allow me to stream out the HTML as the command is run. This means the user gets to see progress as the command runs.

post "/reorder" do
  @project = params["project"]
  @id_or_range = params["id_or_range"]
  @output_log = "[OUTPUT]"

  before, after =  slim(:index).split(@output_log)

  stream do |out|
    out << before
    run(@project, @id_or_range, StreamOutput.new(out))
    out << after
  end
end

https://gist.github.com/NigelThorne/04775270abd46b78e262

Currently I am doing a hack where I render the template (as if I had all the data), then split the template text where the data should be inserted. I then render out the beginning of the template, then render the data as I receive it (on a stream), then the end of the template.

Slim is supposed to support streaming...

I'd like to write.

post "/reorder" do
  ...
  stream do |out|
    out << slim(:index)
  end
end

or better

post "/reorder" do
  ...
  slim(:index, stream: true)
end

How do I get slim to yield to the stream of data when rendering, so I stream out the template in one go?

Upvotes: 3

Views: 308

Answers (1)

user4021304
user4021304

Reputation: 26

Yes, you can if you overwrite the slim helper in Sinatra. See:

Upvotes: 1

Related Questions