我在post方法中调用ruby函数,我正在尝试将函数中的内容输出到网页,但它会在我的控制台中打印输出。如何将其打印到页面?
我试过
<%= RSG(PARAMS [:grammar_file])%>在erb文件中
和
rsg(params [:grammar_file])
在post方法内部,两者都只是打印到控制台
require 'sinatra'
require 'sinatra/reloader' if development? #gem install sinatra-contrib
require './rsg.rb'
enable :sessions
get '/' do
erb :index
end
post '/' do
rsg(params[:grammar_file])
erb :index
end
<% title = "RANDOM SENTENCE GENERATOR" %>
<!doctype html>
<html lang="en">
<head>
<title><%= @title || "RSG" %></title>
<meta charset="UTF8">
</head>
<body>
<h1>RubyRSG Demo</h1>
<p>Select grammar file to create randomly generated sentence</p>
<form action="/" method="post">
<select name="grammar_file">
<option value="Select" hidden>Select</option>
<option value="Poem">Poem</option>
<option value="Insult">Insult</option>
<option value="Extension-request">Extension-request</option>
<option value="Bond-movie">Bond-movie</option>
</select>
<br><br>
<input type="submit" value="submit">
</form>
<section>
<p>Here</p>
<p><%= rsg(params[:grammar_file])%></p>
</section>
</body>
</html>
答案 0 :(得分:0)
您需要告诉您的模板如何处理params。
这就是发生的事情:
post '/' do
rsg(params[:grammar_file])
# your rsg method produces some output. I guess you have a line the `puts` your params to stdout somewhere. Instead you should redirect the output into the template.
erb :index
end
像这样:
post '/' do
erb :index, :locals => {:rsg => rsg(params[:grammar_file])}
end
然后,在您的:index模板中,您有一行:
<%=rsg%>
输出生成的字符串。
问题可能还在于您尝试返回puts
语句而不是普通字符串:
def rsg(p)
puts "I love my daily #{p}. Good luck to you"
end
这只会打印到控制台而不是其他任何内容(true
是准确的)
更好:
def rsg(p)
"I love my daily #{p}. Good luck to you"
end
在这里,您只需从方法中返回String,并且调用rsg("sandwich")
将返回:
# => "I love my daily sandwich. Good luck to you"