【问题标题】:How to render a plain HTML file with Sinatra?如何使用 Sinatra 渲染纯 HTML 文件?
【发布时间】:2011-12-21 06:38:41
【问题描述】:

我有一个简单的 sinatra 应用程序。我要做的就是将它用作包装器,以在特定路线上提供静态 HTML 文件。我的目录结构如下:

/directory
    myhtmlfile.html
    app.rb

我的app.rb 文件如下所示:

require 'sinatra'

get '/myspecialroute' do
    html :myhtmlfile      # i know html is not a method, but this is what I would like to do
end

我怎样才能写这个,以便我可以将我的 html 文件保留为纯 html 文件,但在特殊路径上提供它?

解决方案:

感谢this,我学会了几种不同的方法:

get '/myspecialroute' do
  File.read('myhtmlfile.html')
end

这将打开、读取、关闭文件,然后将文件作为字符串返回。

或者有一个辅助函数可以让这个更干净:

get '/myspecialroute' do
  send_file 'myhtmlfile.html'
end

【问题讨论】:

  • 你可以把它改成.erb,然后调用没有erb的erb方法。
  • 在请求'/myspecialroute' 或'/myspecialroute.html' 时,您希望它呈现HTML 文件吗?
  • @tbuehlmann 我想留下路线/myspecialroute
  • @MarnenLaibow-Koser 在可用端口上启动零配置 Web 服务器。还要添加一条特殊的路线。你有其他选择吗?
  • WEBrick 怎么样?我知道它在某种程度上似乎过时了,但它可能是你在这里需要的。见onestepback.org/index.cgi/Tech/Ruby/WEBrick.rdoc。

标签: ruby sinatra


【解决方案1】:

send_file 做你想做的事吗?

例如

  get '/myspecialroute' do
     send_file 'special.html'
  end

【讨论】:

    【解决方案2】:

    你可以这样做:

    get '/myspecialroute' do
      redirect '/myspecialroute.html'
    end
    

    【讨论】:

    【解决方案3】:

    这对我有用:

    require 'rubygems'
    require 'sinatra'
    
    get '/index.html' do
        @page_title = 'Home'
        @page_id = 'index.html'
        erb :'index.html', { :layout => :'layout.html' }
    end
    

    【讨论】:

      猜你喜欢
      • 2011-06-27
      • 2012-10-31
      • 1970-01-01
      • 2016-05-20
      • 1970-01-01
      • 2023-03-11
      • 1970-01-01
      • 2013-08-20
      相关资源
      最近更新 更多