Phoenix可復用模板

如果你使用過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

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容