Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
681 views
in Technique[技术] by (71.8m points)

elixir - Location for a Phoenix helper in a hex package

I created an alternative phx.gen.html which creates templates with TailwindCSS. It works fine. I'd like to share it by creating a Hex package phx_tailwind_generators. Here is what I have so fare:

$ phx_tailwind_generators:main> tree
.
├── README.md
├── lib
│?? ├── phx_tailwind_generators.ex
├── mix.exs
├── priv
│?? └── templates
│??     └── tailwind.gen.html
│??         ├── controller.ex
│??         ├── controller_test.exs
│??         ├── edit.html.eex
│??         ├── form.html.eex
│??         ├── index.html.eex
│??         ├── new.html.eex
│??         ├── show.html.eex
│??         └── view.ex
└── test
    ├── phx_tailwind_generators_test.exs
    └── test_helper.exs

In those templates I use the tailwind_error_tag/2 helper which is defined here:

defmodule ExampleWeb.TailwindHelper do
  use Phoenix.HTML
  import ExampleWeb.ErrorHelpers

  @doc """
  Generates tag for inlined form input errors.
  """
  def tailwind_error_tag(form, field) do
    Enum.map(Keyword.get_values(form.errors, field), fn error ->
      content_tag(:p, translate_error(error),
        class: "mt-2 text-sm text-red-500",
        phx_feedback_for: input_name(form, field)
      )
    end)
  end
end

But how do I store this helper definition in the hex package? How do I rename defmodule ExampleWeb.TailwindHelper do in a way that it will work in the target system?

The repo: https://github.com/wintermeyer/tailwind_phx_generators


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In order for users of your package to use this helper, they will need to import the module in the def view section of their myapp_web.ex file. Name the module as fitting for your project and in your Readme give them the instructions. An example project you can check out would be: https://github.com/ikeikeikeike/phoenix_html_simplified_helpers.

Quote from their Readme:

3 phoenix_html_simplified_helpers need to import(use) your Phoenix project. The following description is adding 'use syntax' into web.ex.

def view do
  quote do
    use Phoenix.View, root: "web/templates"

    # Import convenience functions from controllers
    import Phoenix.Controller, only: [get_csrf_token: 0, get_flash: 2, view_module: 1]

    # Use all HTML functionality (forms, tags, etc)
    use Phoenix.HTML
    use Phoenix.HTML.SimplifiedHelpers  # <- this line.

    import MyApp.Router.Helpers
    import MyApp.ErrorHelpers
    import MyApp.Gettext
  end
end

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...