Elixir / Phoenix枚举通过元组替换路径

时间:2017-09-01 12:01:02

标签: tuples elixir phoenix-framework enumeration

我正在使用Floki解析一些HTML。并收到以下元组:

{"html", [{"lang", "en"}],
 [{"head", [],
   [{"title", [], ["My App"]},
    {"link", [{"rel", "stylesheet"}, {"href", "/css/app.css"}], []}]},
  {"body", [],
   [{"main", [{"id", "main_container"}, {"role", "main"}], []},
    {"script", [{"src", "/js/app.js"}], [""]},
    {"iframe",
     [{"src", "/phoenix/live_reload/frame"}, {"style", "display: none;"}],
     []}]}]}

是否可以枚举所有元素,以及那些hrefsrc添加完整路径的元素?例如,在这种情况下,请将其替换为:http://localhost/css/app.csshttp://localhost/js/app.js

1 个答案:

答案 0 :(得分:2)

以下是使用递归函数执行此操作的一种方法。

defmodule HTML do

  def use_full_path({el, attrs, children}) do
    {el, update_attrs(attrs), Enum.map(children, &use_full_path/1)}
  end

  def use_full_path(string) do
    string
  end


  defp update_attrs(attrs) do
    Enum.map(attrs, fn {key, val} ->
      if key in ["href", "src"] do
        {key, "http://localhost" <> val}
      else
        {key, val}
      end
    end)
  end
end

tree = {"html", [{"lang", "en"}],
 [{"head", [],
   [{"title", [], ["My App"]},
    {"link", [{"rel", "stylesheet"}, {"href", "/css/app.css"}], []}]},
  {"body", [],
   [{"main", [{"id", "main_container"}, {"role", "main"}], []},
    {"script", [{"src", "/js/app.js"}], [""]},
    {"iframe",
     [{"src", "/phoenix/live_reload/frame"}, {"style", "display: none;"}],
     []}]}]}

HTML.use_full_path(tree) |> IO.inspect