【问题标题】:Render static html page in a controller在控制器中呈现静态 html 页面
【发布时间】:2016-10-21 19:51:10
【问题描述】:

有没有办法读取和呈现位于 控制器中服务器上的另一部分?我不希望通过静态页面功能重定向或提供此页面。

【问题讨论】:

    标签: elixir phoenix-framework


    【解决方案1】:

    您可以使用Phoenix.Controller.html/2 函数发送自定义html 内容。使用File.read!/2读取文件并将内容发送给客户端。

    def index(conn, _params) do
      html(conn, File.read!("path/to/file.html"))
    end
    

    希望这会有所帮助。

    【讨论】:

      【解决方案2】:

      您应该为此使用Plug.Conn.send_file/5。这个函数会比将整个文件读入内存然后使用Phoenix.Controller.html/2发送更有效:

      conn
      |> put_resp_header("content-type", "text/html; charset=utf-8")
      |> Plug.Conn.send_file(200, "/path/to/html")
      

      请注意,我必须手动添加 content-type 标头才能获得与 Phoenix.Controller.html/2 相同的行为。

      【讨论】:

      • 如果您要发送的文件与应用程序本身一起分发,您不想硬编码文件的完整路径,因为它可能会更改。相反,您应该将文件放在priv 目录中,并将Application.app_dir(:your_app, "priv/path/to/file") 作为send_file/3 中的路径传递。
      猜你喜欢
      • 2019-10-14
      • 1970-01-01
      • 2014-02-09
      • 1970-01-01
      • 2012-12-17
      • 1970-01-01
      • 1970-01-01
      • 2020-04-09
      • 1970-01-01
      相关资源
      最近更新 更多