【问题标题】:How do I render a controller action without a layout?如何在没有布局的情况下呈现控制器动作?
【发布时间】:2016-09-15 04:36:01
【问题描述】:

我有一个特定的控制器操作,我想在没有任何布局的情况下进行渲染。

我尝试在控制器级别不使用插件进行渲染,但没有成功。

defmodule Hello.PageController do
  use Hello.Web, :controller

  plug :put_layout, nil

  def landing(conn, _params) do
    render conn, "landing.html"
  end
end

我该怎么做?

【问题讨论】:

    标签: layout controller action elixir phoenix-framework


    【解决方案1】:

    plug :put_layout, nil 不起作用的原因是因为the put_layout plug only considers false to mean "don't use any layout"nil 被视为与任何其他原子一样,Phoenix 尝试渲染 nil.html

    无法为 MyApp.LayoutView 呈现“nil.html”,请为 render/2 定义匹配子句或在“web/templates/layout”处定义模板。编译了以下模板:

    • app.html

    解决方法是使用false:

    plug :put_layout, false
    

    如果你想限制插件执行某些操作,可以通过when

    plug :put_layout, false when action in [:index, :show]
    

    【讨论】:

      【解决方案2】:

      您只需要调用put_layout 并将conn 和false 传递给它。

      def landing(conn, _params) do
        conn = put_layout conn, false
        render conn, "landing.html"
      end
      

      【讨论】:

        【解决方案3】:

        如果您正在运行 LiveVeiw 应用,您的浏览器管道中可能会有 plug :put_root_layout, {MyAppWeb.LayoutView, :root}

        在这种情况下put_layout(false) 只会禁用应用布局,因此您必须使用conn |> put_root_layout(false) 来禁用根布局。

        您可能希望同时禁用两者,因此您需要:

        conn
        |> put_layout(false) # disable app.html.eex layout
        |> put_root_layout(false) # disable root.html.eex layout
        |> render(...)
        

        或更短:

        conn
        |> put_root_layout(false)
        |> render(..., layout: false)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-05-23
          • 1970-01-01
          • 1970-01-01
          • 2012-04-09
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多