Pasando variables a la vista explícitamente via un hash

También es posible pasar en la llamada un hash especificando las variables locales:

get '/:id' do
  foo = Foo.find(params[:id])
  haml '%h1= bar.name', :locals => { :bar => foo }
end
This is typically used when rendering templates as partials from within other templates.

Veamos un ejemplo:

$ ls
Rakefile    config.ru   via_hash.rb views

$ cat via_hash.rb
require 'sinatra/base'

class App < Sinatra::Base
  get '/*' do |name|
    def some_template
       <<-'ERBTEMP'
<ul><% name.each do |item| %>
      <li> <i> <%= item %> </i> </li>
    <% end %>
</ul>
ERBTEMP
    end # method some_template

    puts "*---***#{name}*---****"
    erb some_template, :locals => { :name => name.split('/')}
  end
end

$ cat views/layout.erb 
<!DOCTYPE html>
<html>
  <head>
        <title>Sinatra</title>
  </head>
  <body>
    <h1>Accesing variables in templates via a parameter hash</h1>
    <%= yield %>
  </body>
</html>

$ cat config.ru 
require './via_hash'

run App

$ cat Rakefile task :default => :server

desc "run server"
task :server do
  sh "rackup"
end

desc "make a get /juan/leon/hernandez request via curl"
task :client do
  sh "curl -v localhost:9292/juan/leon/hernandez"
end

$ rake serverrackup
>> Thin web server (v1.5.1 codename Straight Razor)
>> Maximum connections set to 1024
>> Listening on 0.0.0.0:9292, CTRL+C to stop
*---***juan/leon/hernandez*---****
127.0.0.1 - - [05/Jul/2013 17:50:20] "GET /juan/leon/hernandez HTTP/1.1" 200 290 0.0352

$ rake client
curl -v localhost:9292/juan/leon/hernandez
* About to connect() to localhost port 9292 (#0)
*   Trying 127.0.0.1... connected
* Connected to localhost (127.0.0.1) port 9292 (#0)
> GET /juan/leon/hernandez HTTP/1.1
> User-Agent: curl/7.21.4 (universal-apple-darwin11.0) libcurl/7.21.4 OpenSSL/0.9.8x zlib/1.2.5
> Host: localhost:9292
> Accept: */*
> 
< HTTP/1.1 200 OK
< Content-Type: text/html;charset=utf-8
< Content-Length: 290
< X-XSS-Protection: 1; mode=block
< X-Content-Type-Options: nosniff
< X-Frame-Options: SAMEORIGIN
< Connection: keep-alive
< Server: thin 1.5.1 codename Straight Razor
< 
<!DOCTYPE html>
<html>
  <head>
        <title>Sinatra</title>
  </head>
  <body>
    <h1>Accesing variables in templates via a parameter hash</h1>
    <ul>
      <li> <i> juan </i> </li>
    
      <li> <i> leon </i> </li>
    
      <li> <i> hernandez </i> </li>
    
</ul>

  </body>
</html>
* Connection #0 to host localhost left intact
* Closing connection #0



Casiano Rodriguez León 2015-01-07