Proper way to use different Layouts for Templates in Phoenix

人走茶凉 提交于 2019-12-09 11:12:31

问题


Is the proper/simplest way to change the Layout of a Template to use the put_layout method within each Controller action? A simple example of wanting a different Layout for different Controllers seems to become very repetitive (below) so it feels like I'm missing something within the framework.

defmodule MyPhoenix.AController do 
    use MyPhoenix.Web, :controller

    def pageOne(conn, _params) do
        conn
        |> put_layout("LayoutA.html")
        |> render "page1.html" 
    end

    def pageTwo(conn, _params) do 
        conn
        |> put_layout("LayoutA.html")
        |> render "page2.html" 
    end
end

defmodule MyPhoenix.BController do 
    use MyPhoenix.Web, :controller

    def pageOne(conn, _params) do
        conn
        |> put_layout("LayoutB.html")
        |> render "page1.html" 
    end

    def pageTwo(conn, _params) do 
        conn
        |> put_layout("LayoutB.html")
        |> render "page2.html" 
    end
end

回答1:


I think you might be best off by setting a default layout.

defmodule MyPhoenix.AController do 
    use MyPhoenix.Web, :controller

    plug :put_layout, "LayoutA.html"

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

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

defmodule MyPhoenix.BController do 
    use MyPhoenix.Web, :controller

    plug :put_layout, "LayoutB.html"

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

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



回答2:


If for example you need a different layout for say all admin controllers which are covered by separate admin pipeline in the router you can specify plug :put_layout, {MyApp.LayoutView, :admin} for the admin pipeline. I learned it from http://www.cultivatehq.com/posts/how-to-set-different-layouts-in-phoenix/.



来源:https://stackoverflow.com/questions/33399767/proper-way-to-use-different-layouts-for-templates-in-phoenix

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!