I was replying the this specific question “Where/how would I call that macro to be able to inject into all the controllers I need?”.
You don’t have access to the Conn in a live view so you certainly couldn’t use the active class function in my example.
I’m not sure what your use case is but if you wanted to change active/3
in my example to match on the current live view you could do this:
def active(%Socket{view: view}, class) when is_binary(class) do
if view === __MODULE__ do
class
else
""
end
end
which would be used like:
live_redirect(gettext("Back"),
to: Routes.ingredients_index_path(@socket, :index),
class: active(@socket, "your-active-class")
)
Or to match on the actual path you could do something like this:
Helper:
def active(current_path, path, class) when is_binary(class) do
if is_binary(current_path) and current_path === path do
class
else
""
end
end
Usage in a template:
live_redirect(gettext("Back"),
to: Routes.ingredients_index_path(@socket, :index),
class: active(@path, Routes.ingredients_index_path(@socket, :index), "your-active-class")
)
And you need to add path to the assigns in handle_params:
@impl true
def handle_params(_, uri, socket) do
{:noreply, assign(socket, :path, uri_to_path(uri))}
end
defp uri_to_path(raw_uri) do
uri = URI.parse(raw_uri)
uri.path
end
At that point maybe a wrapper around live_redirect/2
makes more sense:
def active_live_redirect(label, opts) do
to = Keyword.get(opts, :to)
active_class = Keyword.get(opts, :active_class)
class = Keyword.get(opts, :class)
current_path = Keyword.get(opts, :current_path)
opts =
if current_path == to do
Keyword.put(opts, :class, "#{class} #{active_class}")
else
opts
end
live_redirect(label, opts)
end
Usage:
active_live_redirect(gettext("Back"),
to: Routes.ingredients_show_path(@socket, :show, @ingredient),
current_path: @path,
active_class: "your-active-class"
)