该库可帮助您将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许可证的许可。
有关完整许可文本,请参见许可证。