【发布时间】:2017-09-18 19:21:06
【问题描述】:
我想在a 标记中包装和元素,但仅在特定条件下。
代码看起来像这样,但我相信一定有更好的方法。
<%= if condition do %>
<a href="/">
<% end %>
<p>Text</p>
<%= if condition do %>
</a>
<% end %>
写这个更好的方法是什么?
【问题讨论】:
标签: html syntax elixir phoenix-framework
我想在a 标记中包装和元素,但仅在特定条件下。
代码看起来像这样,但我相信一定有更好的方法。
<%= if condition do %>
<a href="/">
<% end %>
<p>Text</p>
<%= if condition do %>
</a>
<% end %>
写这个更好的方法是什么?
【问题讨论】:
标签: html syntax elixir phoenix-framework
如果您只想使用它一次,我想不出任何方法可以使它比您已经编写的更优雅,但是如果您想要一个可重用的函数,它可以在 HTML 标记中对某些内容进行条件包装对于任意属性,我会使用这样的辅助函数:
查看:
defmodule MyApp.PageView do
use MyApp.Web, :view
def content_tag_if(condition, name, attrs, [do: content]) do
if condition do
content_tag name, attrs, [do: content]
else
content
end
end
end
模板:
<%= content_tag_if 1 > 2, :a, [href: "/"] do %>
<p>Text</p>
<% end %>
<%= content_tag_if 1 < 2, :a, [href: "/"] do %>
<p>Text</p>
<% end %>
输出:
<p>Text</p>
<a href="/">
<p>Text</p>
</a>
【讨论】:
我当然会使用在适当的 View 模块中声明的函数:
def wrap_in_a_if_condition(html_text, href, condition) do
if condition do
# here build A - propably using [Phoenix.HTML.link/2][1]
else
html_text
end
end
然后您可以将它用于该视图的所有模板。如果需要全局拥有,可以在其他视图中导入。
【讨论】: