【发布时间】:2016-10-21 19:51:10
【问题描述】:
有没有办法读取和呈现位于 控制器中服务器上的另一部分?我不希望通过静态页面功能重定向或提供此页面。
【问题讨论】:
有没有办法读取和呈现位于 控制器中服务器上的另一部分?我不希望通过静态页面功能重定向或提供此页面。
【问题讨论】:
您可以使用Phoenix.Controller.html/2 函数发送自定义html 内容。使用File.read!/2读取文件并将内容发送给客户端。
def index(conn, _params) do
html(conn, File.read!("path/to/file.html"))
end
希望这会有所帮助。
【讨论】:
您应该为此使用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 中的路径传递。