【问题标题】:Configuring erb directory in Sinatra在 Sinatra 中配置 erb 目录
【发布时间】:2023-03-24 07:50:01
【问题描述】:

app/controllers/app.rb

require 'sinatra'
get '/' do
  erb :index
end

app/views/index.erb

<html>
    <body>
        <p>Hello World</p>
    </body>
</html>

错误:

Errno::ENOENT at /
No such file or directory - .../app/controllers/views/index.erb

如何配置 erb 以查看 app/views 而不是 app/controllers/views

【问题讨论】:

    标签: ruby sinatra erb


    【解决方案1】:

    您可以通过调整配置设置来实现此目的。由于您使用的是非标准设置,因此您需要告诉 Sinatra 您的应用程序的实际根目录是什么以及在哪里可以找到视图。在app/controllers/app.rb 文件的顶部添加:

    # sets root as the parent-directory of the current file
    set :root, File.join(File.dirname(__FILE__), '..')
    # sets the view directory correctly
    set :views, Proc.new { File.join(root, "views") } 
    

    您可以在Sinatra Documentation 中阅读有关 Sinatra configuration options 的更多信息。

    【讨论】:

      【解决方案2】:
      set :views, Proc.new { File.join(root, "views") }
      

      来自http://www.sinatrarb.com/configuration.html#__view_template_directory

      编辑:显然这没有任何作用,呵呵。最好在app/ 中有一个需要您的控制器的文件:

      Dir.glob("controllers/*.rb").each { |r| require_relative r }
      

      然后,app/views 将成为默认视图目录。

      【讨论】:

      • 这将失败,因为 Sinatra 将根目录视为 app/controllers,因此将在该路径下查找 views 目录。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-10
      • 1970-01-01
      • 2011-02-03
      • 2021-10-31
      • 1970-01-01
      • 2015-12-06
      相关资源
      最近更新 更多