Question

I would like to use this style in sinatra:

get("/") {
  <html>
    <body>
      <h1>Hello, world!</h1>
      Say <a href="hello-scalate">hello to Scalate</a>.
    </body>
  </html>
}

http://www.scalatra.org/2.2/getting-started/first-project.html#toc_64

But it wasn't clear to me whether this is possible to use unquoted literal HTML strings in the body of the get function.

Was it helpful?

Solution

Ruby and Sinatra don't support that exact format because it'd be a syntax error. You have to quote the string containing the markup somehow, otherwise Ruby will complain. But, you can do that with just a little addition of Ruby code:

require 'sinatra'

get("/") {
  %{
    <html>
      <body>
        <h1>Hello, world!</h1>
        Say <a href="hello-scalate">hello to Scalate</a>.
      </body>
    </html>
  }
}

You could do it this way too:

require 'sinatra'

get("/") {
  return <<EOT
<html>
  <body>
    <h1>Hello, world!</h1>
    Say <a href="hello-scalate">hello to Scalate</a>.
  </body>
</html>
EOT
}

One way or the other the content has to be "stringified".

This is one of the things I really like about Sinatra. It's a great prototyping tool for web services. Whatever is returned by the handler goes to the browser. If it's not HTML then you can easily specify what type it is using the content_type method and the MIME type for the content, then return that content.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top