如果你使用過React或者Vue這類流行的前端框架,你會對可復用模板/組件的概念感到熟悉。實際上,在Phoenix中,我們也可以使用View和eex構建可復用模板,當然咯,狀態(tài)流和數(shù)據(jù)流監(jiān)聽什么的還做不到,但是對于Dumb Components來說,很大一部分可以搞定。
我們來看一下一個基本的模板。
<Tabs>
<Tab name="All Products" />
<Tab name="Featured" />
</Tabs>
這樣的好處是,當你需要修改Tabs或Tabs時,你只需要修改一處地方,然后整個應用的模板都會修改了。
在Phoenix中,我們可以實現(xiàn)這個功能。
1. 創(chuàng)建 ComponentView 和 templates/component 目錄
defmodule MyApp.Web.ComponentView do
use MyApp.Web, :view
end
2. 定義 Component 的模板
<!-- templates/component/tabs.html -->
<ul class="tabs">
<%= assigns[:do] %>
</ul>
<!-- templates/component/tab.html -->
<li class="tab"><%= assigns[:name] %></li>
3. 當你需要tabs時使用這些模板
<%= render ComponentView, "tabs.html" do %>
<%= render ComponentView, "tab.html", name: "All Products" %>
<%= render ComponentView, "tab.html", name: "Featured" %>
<% end %>
目前,它能工作,但是比較冗余,我們來增加 ComponentHelpers 模塊
# views/component_helpers.ex
defmodule MyApp.Web.ComponentHelpers do
def component(template, assigns) do
MyApp.Web.ComponentView.render(template, assigns)
end
def component(template, assigns, do: block) do
MyApp.Web.ComponentView.render(template, Keyword.merge(assigns, [do: block]))
end
end
然后,在 MyApp.Web 的 view 模塊中導入
def view do
quote do
# ...
import MyApp.Web.ComponentHelpers
end
end
現(xiàn)在的 markup 變?yōu)榱?/p>
<%= component "tabs.html" do %>
<%= component "tab.html", name: "All Products" %>
<%= component "tab.html", name: "Featured" %>
<% end %>
你還可以將它繼續(xù)精簡
<%= c "tabs.html" do %>
<%= c "tab.html", name: "All Products" %>
<%= c "tab.html", name: "Featured" %>
<% end %>
它雖然沒有像React那樣精簡,但是也差不多了
<Tabs>
<Tab name="All Products" />
<Tab name="Featured" />
</Tabs>
這只是一個非常簡單的示例,并不需要花很大力氣,當你需要使用復雜的 markup 時,你可以考慮這種方式。
Ref
http://blog.danielberkompas.com/2017/01/17/reusable-templates-in-phoenix.html