【问题标题】:ruby sinatra base get '/foo/bar' public directoryruby sinatra base 获取'/foo/bar'公共目录
【发布时间】:2014-11-28 19:44:49
【问题描述】:

GITHUB:https://github.com/coasterb/foo_bar_stackoverflow

我无法使用“/foo/bar”路径访问我的公共目录中的样式表。

我认为这是我没有定义 public_folder 的问题,但事实并非如此。

require 'sinatra'
require 'haml'
set :static, true
set :public_folder, "public"  

get '/foo' do 
    haml :foo
end

get '/foo/bar' do
    haml :bar
end

# 目录层次结构 - 这不起作用

+Webapp
--app.rb
-+public
---stylesheet.css 
-+views
---foo.haml
---bar.haml

# 目录层次结构 - 这确实有效,但我现在有我的文件的副本。

+Webapp
--app.rb
-+public
---stylesheet.css 
--+foo
----stylesheet.css
-+views
---foo.haml
---bar.haml

localhost:9396/foo/bar:

#foo/bar.html from the web browser. 
<html> 
    <head>
        <link href='./stylesheet.css' rel='stylesheet' type='text/css'>
    </head> 
<html> 

在 Chrome 的控制台中抛出“404 not found”错误,但不会在 /foo 控制台中抛出错误。

haml bar.haml:

!!!
%html 
  %head
    %link{:href=>"./stylesheet.css", :rel => "stylesheet", :type => "text/css"}

【问题讨论】:

  • Haml 文件中的链接是什么样的?我怀疑您使用的是相对链接。
  • %link{:href=&gt;"./stylesheet.css" 不是指向/foo/bar/stylesheet.css,哪个不存在?尝试使用绝对路径:%link{:href=&gt;"/stylesheet.css"(不带点)。
  • 我删除了“.”以反映“绝对位置。我还删除了下面回答的“/”。我仍然收到 404 错误。
  • 你有这个 github repo 的链接吗?

标签: ruby sinatra haml


【解决方案1】:

Use a layout for the head section:

layout.haml

!!!
%html
  %head
    %link{:href=>"/stylesheet.css", :rel => "stylesheet", :type => "text/css"}
  %body 
    = yield

foo.haml 或任何其他视图

%p Hello World

而不是像这样将所有内容放在每个视图中:

坏人

!!!
%html
  %head
    %link{:href=>"/stylesheet.css", :rel => "stylesheet", :type => "text/css"}
  %body 
    %p Hello World

另外,Sinatra is at version 1.4.5 now,除非您迫切需要坚持使用 1.3,否则不要。使用 Ruby v1.9 也是如此,它更容易理解,但是当 v2 可用并且可以正常运行所有 1.9 代码时,确实没有太多好的理由使用它。

【讨论】:

    【解决方案2】:

    将前导./ 关闭;这将指向/foo/bar/stylesheet.css,正如上面cmets中提到的@Arman。

    此外,您不需要使用您使用的 :public_folder 设置,因为您只是将其设置为默认值。

    %link{:href => '/stylesheet.css', :rel => 'stylesheet', :type => 'text/css'}
    

    如果您想手动为 css 文件设置一个目录,或者例如在 public 下设置子目录,您可以使用

    :css_dir
    

    【讨论】:

    • 我删除了 :public_folder 仍然没有骰子。尽管我确实在“public”中添加了另一个名为“foo”的目录,并将 stylesheet.css 的副本放在 foo 目录中。那行得通。但现在我有了 stylesheet.css 的副本。这不好。我也提出了一个回购。感谢您的意见。
    • 对不起;我对不需要/ 感到失望。我已经更新并在github.com/bigtunacan/foo_bar_stackoverflow 放了一个叉子,你也可以看看。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-08
    • 2017-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-01
    • 2022-11-04
    相关资源
    最近更新 更多