问题描述
我使用Sinatra和Haml编写了一个网络表单,该表单将用于调用Ruby脚本.
I wrote a webform using Sinatra and Haml that will be used to call a Ruby script.
除一件事情外,其他一切似乎都不错:我需要从Sinatra/Ruby脚本中将参数传递给Haml视图文件.
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
如果脚本遇到错误,它将返回一个字符串,其中包括单词"Error".如果发生这种情况,我正在调用Haml文件,该文件将向用户显示错误页面.如果脚本没有遇到错误,它将返回成功页面.
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.
我想在成功/失败页面中包括用户添加的新VM的名称.我的问题是我不知道如何在两个Haml文件中传递它.我搜索了一个解决方案,但没有找到任何东西.
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.
推荐答案
您可以使用:locals
键将参数的哈希值传递给Haml方法:
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
通过这种方式,Haml文件中的Ruby代码可以访问some_object
并呈现其中的任何内容,调用方法等.
This way the Ruby code in your Haml file can access some_object
and render whatever content is in there, call methods etc.
这篇关于调用视图文件时如何传递参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!