问题
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
回答1:
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
回答2:
You are after eex
templating the sources. See how phoenix does it for e. g. context template.
Then you need to process it as shown here. In a nutshell, it’ll be all about calling EEx.eval_file/3.
Mix.Generator.create_file(target, EEx.eval_file(source, binding))
来源:https://stackoverflow.com/questions/65591612/location-for-a-phoenix-helper-in-a-hex-package