swapnesh
swapnesh

Reputation: 26722

How to put html tags in sinatra strings

I just started Sinatra and try to render the name with h1 html tag but its not working. Although the string is coming without html tag but it is also not rendering the html tag as desired let me know how do I handle it in Sinatra

My code -

get '/nesh' do
    name = "Swapnesh"
    "Hello <h1> #{name} </h1> Sinha"
end

Upvotes: 2

Views: 1372

Answers (3)

Stuart M
Stuart M

Reputation: 11588

The string you're returning from the get '/nesh' block is exactly what will be returned in the HTTP request, which is why it is not wrapped in <html>...</html> tags. If you want there to be surrounding tags such as <html>, <body>, etc., then you should create a Sinatra view template, and pass your view information (such as name) into the view renderer.

A complete example might look like this:

app.rb:

set :views, settings.root + '/templates'

get '/nesh' do
  name = "Swapnesh"
  erb :hello, :locals => {:name => name}
end

templates/layout.erb:

<html>
<body>
  <%= yield %>
</body>
</html>

templates/hello.rb:

<h1>Hello <%= name %> Sinha</h1>

Notice I also used a Sinatra layout, which is a base template for all rendered actions (unless opted-out).

Finally, you could implement it all in one file using named templates:

template :layout do
  <<-EOF
<html>
<body>
  <%= yield %>
</body>
</html>
EOF
end

template :hello do
  "<h1>Hello <%= name %> Sinha</h1>"
end

get '/nesh' do
  name = "Swapnesh"
  erb :hello, :locals => {:name => name}
end

Upvotes: 4

swapnesh
swapnesh

Reputation: 26722

I am not sure if this is the correct way or not but i tried this way and it works..

require 'sinatra'

get '/nesh' do
    @name = "Swapnesh"
    erb :test
end

__END__
@@test
<!doctype html>
<html lang="en">
<head>
<title>Test Sinatra pass</title>
<meta charset="utf-8">
</head>
<body>
<p> Hello <h1> <%= @name %> </h1> Sinha</p>
</body>
</html>

Upvotes: 1

BlackHatSamurai
BlackHatSamurai

Reputation: 23483

If you want to use HTML and Sinatra, you should use erb, or something similar to display the HTML.

Example your code:

get '/nesh' do
    name = "Swapnesh"
    erb :resultPage, :locals => {:name => name}
end

Example resultPage.erb:

<p> Hello <h1> <%=#{name}%> </h1> Sinha</p>

Upvotes: 2

Related Questions