【问题标题】:Rails render HTML file outside of 'public'Rails 在“公共”之外呈现 HTML 文件
【发布时间】:2015-11-16 02:09:49
【问题描述】:

我正在尝试在 Rails 5.0.0.alpha 中做一些非常简单的事情:渲染不在 public 目录中的 HTML 文件。

我的路线是这样的:

get '/api/docs' => 'static#documentation'

而我的StaticController 看起来像这样:

class StaticController < ApplicationController
    def documentation
        render 'api/documentation/index.html'
    end
end

我要渲染的index.html文件位于app/views/api/documentation/index.html

每当我在浏览器中加载/api/docs 时,我得到的只是一个带有空白页面的200 OK 响应,这意味着没有呈现任何内容。

我几乎尝试了render 的所有变体:

  • render 'app/views/api/documentation/index.html'
  • render 'views/api/documentation/index.html'
  • render 'api/documentation/index.html'
  • render '/documentation/index.html'
  • render 'app/views/api/documentation/index'
  • render 'views/api/documentation/index'
  • render 'api/documentation/index'
  • render '/documentation/index'
  • render file: 'app/views/api/documentation/index'
  • render file: 'views/api/documentation/index'
  • render file: 'api/documentation/index'
  • render file: '/documentation/index'

等等。我错过了什么?

编辑:服务器输出:

Started GET "/api/docs" for 198.167.XXX.XX at 2015-11-16 02:07:48 +0000
Processing by StaticController#documentation as HTML
Completed 200 OK in 1ms (Views: 0.2ms | ActiveRecord: 0.0ms)

【问题讨论】:

  • 服务器输出是什么?
  • @Jason 查看我的编辑。就像我在问题中所说,这是一个200 OK 响应,没有错误...
  • 我看到您在问题中提到了这一点,但查看完整的服务器输出显示我们缺少Rendered api/documentation/index.html 行。此外,您可以确定它是否找到文件的一种方法是重命名它并查看是否收到“模板丢失”错误。如果这不会引发错误,那么您可能遇到了路径问题。如果您在重命名文件时确实收到该错误,那么它实际上是在查找文件。在这种情况下,请尝试 puts render_to_string('api/documentation/index.html') 并查看文件内容是否显示在服务器输出中。

标签: ruby-on-rails


【解决方案1】:

对于其他与 OP 有类似问题的人。如果您使用的是 api_only rails 应用程序,请确保您的控制器继承自 ActionController::Base 而不是 ActionController::API

【讨论】:

    【解决方案2】:

    我认为这是因为主应用程序模板。您可以通过 2 种方式修复, 1.检查&lt;%= yield %&gt;标签是否在application.html.erb中

    或者,使用禁用它

    layout false
    

    在您的静态控制器中

    【讨论】:

    • 你知道吗,我完全忘了提到我正在使用 Rail 的 API 功能(这意味着在创建应用程序时没有生成这些应用程序级渲染文件)。你肯定是正确的。我可以提供静态文件(如果我将它们放在/public 中),但我想将此文件放在控制器后面以进行身份​​验证。由于我没有任何应用级布局文件,因此调用render 绝对没用。我会深入研究并回复你。谢谢你的建议!
    • 好的,你可以试试这个。我假设它会寻找 erb 文件。这样我们就可以提到它是静态文件。渲染 :file => 'api/documentation/index.html'
    猜你喜欢
    • 2011-02-10
    • 2013-08-21
    • 1970-01-01
    • 2015-01-28
    • 2011-03-10
    • 2018-07-29
    • 2018-09-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多