在HTML页面中包含Ruby on Rails函数,需要将Ruby代码嵌入到HTML中,并在服务器端执行。以下是一个简单的示例:
pages_controller.rb
,并添加一个名为index
的方法:class PagesController< ApplicationController
def index
end
end
views/pages
目录中创建一个名为index.html.erb
的文件,并添加以下HTML代码:<!DOCTYPE html>
<html>
<head>
<title>Ruby on Rails Function</title>
</head>
<body>
<h1>Ruby on Rails Function</h1>
<p>The result of the Ruby function is: <%= my_function() %></p>
</body>
</html>
pages_controller.rb
文件中定义my_function
方法:class PagesController< ApplicationController
def index
end
def my_function
"Hello, World!"
end
end
config/routes.rb
文件中添加一个路由,以便访问index
方法:Rails.application.routes.draw do
get 'pages/index'
end
现在,当您访问http://localhost:3000/pages/index
时,您将看到一个包含Ruby函数结果的HTML页面。
请注意,这只是一个简单的示例,实际应用程序可能需要更复杂的逻辑和更多的安全措施。此外,在实际开发中,您可能需要使用Ruby on Rails的其他功能,例如模型、视图、控制器和资产管道等。
领取专属 10元无门槛券
手把手带您无忧上云