Question

Im building a simple practice Sinatra app which allows users to enter urls via a form, and once submitted the app will open each of these urls in a new table (similar to urlopener.com)

My app.rb file

require 'sinatra'

get '/' do
    erb :'index.html'
end

post '/' do
    urls = params[:urls]
end

My View file

<h1>Enter URLs Below </h1>
<form action="/" method="post">
<textarea rows="40" cols="50" id="urls" name="urls" ></textarea>
<br/>
<input type= "submit" value="Open 'em up!">
</form>

I am able to print the urls to the console in the post action, but am unsure how to redirect back to the index, and display each of the urls before opening them in new tabs (which I plan on using JS to do).

Was it helpful?

Solution

You don't have to redirect back to the original page (in fact, the URL hasn't changed, so redirecting doesn't make sense). Instead, you render the same template. Simply insert erb :'index.html' in the second block (post '/') as well, and put the URLs in a class variable, so that they will be available to the template:

@urls=params[:urls].split

(The split is there so you get an array of strings, rather than one long string with linebreaks.)

Finally, you add some logic to the template to check whether there are any URLs to display, and if so render them as a list:

<% if @urls && !@urls.empty? %>
  <h1>URLs</h1>
  <ul>
  <% for @url in @urls %>
    <li>
      <%= @url %>
    </li>
  <% end %>
  </ul>
<% end %>

<h1>Enter URLs Below </h1> 
...etc...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top