如何使用Phoenix.HTML呈现元素列表

时间:2017-04-16 06:50:12

标签: phoenix-framework

我试图在View文件中呈现元素列表。我可以渲染它们,我将它们包装在另一个元素中:

iex(9)> span1 = content_tag(:span, "test1")
{:safe, [60, "span", [], 62, "test1", 60, 47, "span", 62]}
iex(10)> span2 = content_tag(:span, "test2")
{:safe, [60, "span", [], 62, "test2", 60, 47, "span", 62]}
iex(11)> content_tag(:div, [span1, span2]) |> safe_to_string
"<div><span>test1</span><span>test2</span></div>"

但是,我怎样才能渲染两个跨度?以下不起作用。

iex(12)> [span1, span2] |> safe_to_string
** (FunctionClauseError) no function clause matching in Phoenix.HTML.safe_to_string/1
    (phoenix_html) lib/phoenix_html.ex:160: Phoenix.HTML.safe_to_string([safe: [60, "span", [], 62, "test1", 60, 47, "span", 62], safe: [60, "span", [], 62, "test2", 60, 47, "span", 62]])
iex(12)>

1 个答案:

答案 0 :(得分:3)

您需要首先将列表传递给Phoenix.HTML.html_escape/1Phoenix.HTML.Tag.content_tag/2在内部执行相同的操作):

iex(1)> import Phoenix.{HTML, HTML.Tag}
[Phoenix.HTML, Phoenix.HTML.Tag]
iex(2)> span1 = content_tag(:span, "test1")
{:safe, [60, "span", [], 62, "test1", 60, 47, "span", 62]}
iex(3)> span2 = content_tag(:span, "test2")
{:safe, [60, "span", [], 62, "test2", 60, 47, "span", 62]}
iex(4)> html_escape([span1, span2])
{:safe,
 [[60, "span", [], 62, "test1", 60, 47, "span", 62],
  [60, "span", [], 62, "test2", 60, 47, "span", 62]]}
iex(5)> html_escape([span1, span2]) |> safe_to_string
"<span>test1</span><span>test2</span>"