該庫可幫助您將HTML的封裝位寫入服務器中的一個名為組件的單元中,呈現為Phoenix網站。類似於反應/Ember/Web組件的情況。
您可以使用內置生成器生成新組件
$ mix phoenix.gen.component button
* creating web/components/button/view.ex
* creating web/components/button/template.html.eex
* creating test/components/button_test.exs
然後,您可以在模板中使用新組件
# /web/views/page_view.ex
defmodule MyApp.PageView do
use MyApp.Web , :view
use PhoenixComponents.View
import_components [ :button ]
end # /web/templates/page/show.html.eex
<%= button type: :primary do % >
My cool button!
<% end % >具有相應的組件定義
# /web/components/button/view.ex
defmodule MyApp.Components.ButtonView do
use PhoenixComponents.Component
def class_for_type ( type ) do
"btn btn--" <> to_string ( type )
end
end # /web/components/button/template.html.eex
< button class = " <%= class_for_type @attrs.type %> " >
<%= @content % >
</ button >將phoenix_components添加到您的mix.exs中。 exsdeps:
def deps do
[ { :phoenix_components , "~> 1.0.0" } ]
end然後,您必須在配置文件中添加一個配置
config :phoenix_components , app_name: MyApp其中MyApp是代表您的Phoenix應用的模塊。
如果您正在運行Elixir 1.3或更低,請不要忘記將其添加在您的應用程序列表中。 exs。
def application do
[ applications: [ :phoenix_components ] ]
end 這是如何在應用程序中創建和使用組件的快速概述。
安裝依賴關係後,您需要配置應用程序。
您可以通過將此行添加到您的web/web.ex文件來做到這一點
查找行def view do並將其更新以包含此行
def view do
quote do
use Phoenix.View , root: "web/templates"
use PhoenixComponents.View # Add this line
...button組件鳳凰組件由兩個不同的部分定義,即視圖和模板。該視圖包含輔助功能,模板包含HTML。
要創建一個按鈕組件,您需要使用以下內容創建視圖文件web/components/button/view.ex
defmodule MyApp.Components.Button do
use PhoenixComponents.Component
def classes do
"btn btn-default"
end
end然後創建模板文件web/components/button/template.html.eex具有以下內容
< button class = " <%= classes %> " >
<%= @content % >
</ button >請注意, @content變量將包含按鈕塊中定義的內容。下一節更詳細地顯示了這一點。
您可以使用輔助功能component使用任何模板中的組件。
在任何模板中,例如web/templates/pages/show.html.eex添加按鈕組件。
<%= component :button do % >
My cool button!
<% end % >組件塊中的內容作為@content變量傳遞給組件。
您可以使用import_components函數在任何視圖中導入組件。這使您避免了必須調用component助手,而只需使用組件的名稱即可。
defmodule MyApp.PageView do
use Phoenix.Web, :view
import_components [:button, :jumbotron]
end那麼您可以從模板中使用這些幫助者
<%= button type: :submit do % >
Submit form!
<% end % >調用組件時,您可以傳遞您喜歡的任何屬性。
<%= button type: :submit do % >
Submit form!
<% end % >在組件的模板內部,這些屬性將在@attrs地圖中可用。
< button type = " <%= @attrs.type %> " >
<%= @content % >
</ button >您可以通過編輯應用程序配置文件config/config.exs來配置在哪裡放置組件。
config :phoenix_components , path: "lib/foo/bar"默認情況下從web獲得組件。
Phoenix_components已獲得MIT許可證的許可。
有關完整許可文本,請參見許可證。