このライブラリは、HTMLのカプセル化されたビットを、サーバーレンダリングされたPhoenix Webサイトのコンポーネントと呼ばれる単一のユニットに書き込みます。 React/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 >mix.exs depsにphoenix_componentsを追加します:
def deps do
[ { :phoenix_components , "~> 1.0.0" } ]
endそして、構成ファイルに1つの構成を追加する必要があります
config :phoenix_components , app_name: MyApp MyApp 、Phoenixアプリを表すモジュールです。
Elixir 1.3以降を実行している場合は、Mix.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コンポーネントの作成Phoenixコンポーネントは、ビューとテンプレートという2つの異なる部分で定義されます。ビューにはヘルパー関数が含まれており、テンプレートには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ライセンスに基づいてライセンスされています。
完全なライセンステキストについては、ライセンスを参照してください。