继承Phoenix/Elixir中的布局

继承Phoenix/Elixir中的布局,elixir,phoenix-framework,Elixir,Phoenix Framework,我需要为我的Phoenix/Elixir应用程序创建一个简单的布局层次结构,并从不同的布局继承我的模板。我知道如何对单个布局和多个模板执行此操作。但是,如何从一个布局继承另一个布局呢 比如说,层次结构是layout1->layout2->layout3和template2(layout2)、template3(layout3) 文件中没有提到这一点 更新: 基本布局是基本布局——类似于OOP中的基类,它不知道它的子布局——有多少布局,如果有的话。因此,从基本布局调用“render childre

我需要为我的Phoenix/Elixir应用程序创建一个简单的布局层次结构,并从不同的布局继承我的模板。我知道如何对单个布局和多个模板执行此操作。但是,如何从一个布局继承另一个布局呢

比如说,层次结构是layout1->layout2->layout3和template2(layout2)、template3(layout3)

文件中没有提到这一点

更新


基本布局是基本布局——类似于OOP中的基类,它不知道它的子布局——有多少布局,如果有的话。因此,从基本布局调用“render children1”是没有意义的。

在调用render:

<%= render @view_module, @view_template, Map.put(assigns, :layout, {MyApp.LayoutView, "nested.html"}) %>

对于3种布局,您可以执行以下操作:

# Controller
render(conn, "index.html", nested_1: "nested_1.html", nested_2: "nested_2.html")

# app.html.eex
<%= render @view_module, @view_template, Map.put(assigns, :layout, {MyApp.LayoutView, assigns.nested_1}) %>

# nested_1.html.eex
<%= render @view_module, @view_template, Map.put(assigns, :layout, {MyApp.LayoutView, assigns.nested_2}) %>

# nested_2.html.eex
<%= render @view_module, @view_template, assigns %>
#控制器
render(conn,“index.html”,嵌套的_1:“嵌套的_1.html”,嵌套的_2:“嵌套的_2.html”)
#app.html.eex
#嵌套的_1.html.eex
#嵌套的_2.html.eex

我解决这个问题的方法是在视图中添加一个辅助对象来呈现父布局:

defmodule MyApp.LayoutView do
  use MyApp.Web, :view

  def base_layout(conn, opts, do: contents) when is_list(opts) do
    render "base.html", [conn: conn, contents: contents] ++ opts
  end
end
helper中的“contents”参数将是您在do/end块中放置的任何内容,因此您可以在HTML中使用它作为“子布局”,如:

这有点像黑客,但到目前为止,这是我找到的解决问题的最好办法


请注意,我还添加了一个
opts
参数,以便能够在特定情况下覆盖某些赋值(我主要使用它来定义要附加在
上的html css类,具体取决于呈现的子布局)。

您可以继续嵌套布局。在嵌套模板中进行相同的渲染调用,以嵌套另一个模板。您应该在最里面的模板中有
您将有相同的调用来在嵌套模板中渲染以嵌套另一个模板--我的基础模板不知道将嵌套哪些模板。您可以通过分配传递它。例如,在您的控制器中:
render(conn,“index.html”,user\u布局:{MyApp.LayoutView,“user.html”},other\u布局:{MyApp.LayoutView,“other.html”})
什么控制器?没有与布局关联的控制器。如果我有20个控制器,每个控制器有20个动作呢?大概你在某处有一个控制器。您也可以从一个插件填充赋值,我在这里使用了一个控制器操作来演示。不知何故,在应用程序的某个地方,您必须定义要使用的模板和布局。你的问题太抽象了,这是我目前能给你的最好答案。如果层次结构中有4个布局呢?意大利面代码?
defmodule MyApp.LayoutView do
  use MyApp.Web, :view

  def base_layout(conn, opts, do: contents) when is_list(opts) do
    render "base.html", [conn: conn, contents: contents] ++ opts
  end
end
<%= base_layout @conn, [foo: "bar"] do %>

    <div class="sublayout-wrapper">
      <%= render @view_module, @view_template, assigns %>      
    </div>
    <!-- specific footer for sub-layout goes here etc -->

<% end %>
<html>
<head>
    <title>My App</title>
</head>
<body>
    <div class="header"></div>
    <%= @contents %>
</body>