0
votes

This may not be a Breadcrumble question, but how do I pass a parameter from a previous plug into the breadcrumbable? For example, if the previous plug set_merchant sets the merchant on conn.params.merchant, how can I pass that id to breadcrumable?

   plug :set_merchant
   plug :add_breadcrumb, name: "Dashboard", url: "/dashboard/#{conn.params.merchant_id}"

.....

 defp set_merchant(conn, _opt) do
    case conn.params do
      %{"merchant_id" => merchant_id} ->
        case MyApp.find_merchant(merchant_id) do
          nil ->
            conn |> redirect(to: "/dashboard/#{merchant_id}") |> halt
          merchant ->
            assign(conn, :merchant, merchant)
        end
      _ ->
        conn |> redirect(to: "/") |> halt
    end
  end

The conn.params.merchant_id is where I would want to pass the param from the first plug set_merchant

2

2 Answers

2
votes

You can pass as many parameters as you want as you do already with Plug.Conn.assign/3 function.

The simplest solution for you is to do something like this in your case:

case MyApp.find_merchant(merchant_id) do
  nil ->
    conn 
    |> redirect(to: "/dashboard/#{merchant_id}") 
    |> halt()
  merchant ->
    conn
    |> assign(:merchant, merchant)
    |> assign(:merchant_id, merchant_id) # this is what you asked for
end

Then you will not call your plug by adding this url with merchant_id, because the conn would already have it because set_merchant would provide it to you.

Also, another option:

If you don't want to have merchant_id there, you can simply get it from merchant, by doing:

merchant_id = conn.assigns.merchant.id

You have to differentiate params from assigns. I'm not sure how do you get the merchant, but to remember this quickly:

  • params come from the outside e.g. POST request, query strings etc.
  • assigns are set by you or anyone else who modified Plug.Conn with assign/3 function
1
votes

You can call the add_breadcrumb plug directly from the set_merchant plug like this:

assign(conn, :merchant, merchant)
|> Breadcrumble.Plugs.add_breadcrumb(name: "Dashboard", url: "/dashboard/#{merchant_id}")