Phoenix:如何在视图函数中使用模板助手中插入的值

Phoenix: how to use values inserted in a template helper in a view function

假设我有这个模板sample.html.eex:

<div class="<%= @class %>" id="<%= @id %>">
   <a href="home.html" class="<%= @class_a"></a>
</div>

虽然我想在我的模板中使用它们,但我希望 @class@id 来自调用模板时插入的值,而 @class_a 来自视图函数将其生成为 @class@id 的串联。我是说: 1) 当我在其他模板中调用此模板时,我将这些值传递给它:

<%= render myApp.ComponentView, "sample.html",
    id: "six",
    class: "six" %>

2) 我的 component_view 中有一个函数:

def class_a (conn) do
        class+id
end

然后,class_a 可以访问模板。 我的问题是如何在我看来访问 classid 值。 我在尝试执行此操作时遇到了几个错误。如何正确操作?

您不能将 @class@id 传递给您的 class_a 函数吗?

def class_a(class, id) do
  "#{class}#{id}"
end

class_a(class, id)

然后您可以从您的模板中调用此函数:

<div class="<%= @class %>" id="<%= @id %>">
   <a href="home.html" class="<%= class_a(@class, @id)"></a>
</div>

请记住,使用 @ 并不是什么魔法。 @ 是 Eex 在赋值中使用变量的方式。如果您的视图中有一个函数 class_a,那么您将使用 class_a 调用它。 @class_a 存在的唯一方法是将其添加到 conn 结构上的 assigns

如果你想要一个接受单个连接的函数,你可以使用 conn.assigns 来获取值:

def class_a(conn) do
  class = conn.assigns.class
  id = conn.assigns.id

  "#{class}#{id}"
end