Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass an argument when calling a view file?

Tags:

ruby

sinatra

haml

I wrote a webform using Sinatra and Haml that will be used to call a Ruby script.

Everything seems fine except for one thing: I need to pass an argument to a Haml view file from the Sinatra/Ruby script.

Here is a part of my code:

#!/usr/bin/env ruby
require 'rubygems'
require 'sinatra'
require 'haml'

get '/' do
  haml :index
end

post '/' do
  name = params[:name]
  vlan = params[:vlan]

  tmp = nil
  tmp = %x[./wco-hosts.rb -a -n #{name} -v #{vlan}]

  if tmp.include?("Error")
    haml :fail
  else
    haml :success
  end
end

If the script encounters an arror it will return a string including the word "Error". If this happens, I'm calling a Haml file which will show an error page to the users. If the script doesn't encounter an arror, it will return a success page.

I want to include, in the success/fail page, the name of the new VM the user added. My problem is that I have no clue how to pass it in both my Haml files. I searched for a solution, but did not find anything.

like image 546
Cocotton Avatar asked Feb 29 '12 17:02

Cocotton


4 Answers

You can pass a hash of parameters to the Haml method using the :locals key:

get '/' do
    haml :index, :locals => {:some_object => some_object}
end

This way the Ruby code in your Haml file can access some_object and render whatever content is in there, call methods etc.

like image 170
grefab Avatar answered Nov 10 '22 16:11

grefab


Haml supports passing variables as locals. With Sinatra, you can send these locals like so:

haml :fail, :locals => {:vm_name => name}

and in the view, reference the variable using locals[:vm_name] or simply vm_name.

like image 33
sgtFloyd Avatar answered Nov 10 '22 15:11

sgtFloyd


I'm doing this in Sinatra+Markaby, I think it should be the same with Haml:

In Ruby script: @var = 'foo'

In template: User name: #{@var}

like image 4
Oleg Mikheev Avatar answered Nov 10 '22 15:11

Oleg Mikheev


Given

haml(template, options = {}, locals = {})

I'd try

haml :success, {}, {my_var: my_value}
like image 1
Reactormonk Avatar answered Nov 10 '22 17:11

Reactormonk