How can I use values passed to a controller to string inside

Hi again! Consider the codes below:

def new(conn, %{"invoice" => invoice_params}) do
    variable = "Hello *string here* Hooray *string2 here* day" 

My goal is that parameters passed to that controller can be used as a string.

I tried #{invoice_params.payorcode} but it’s not working

What is payorcode, and what error are you getting?

If payorcode is not a simple data type that has a to_string impl, you may need to use #{inspect invoice_params.payorcode}

payorcode is a key from %{"invoice" => invoice_params}

Here’s the value of my map:

%{"DateFrom" => "", "DateTo" => "", "payorcode" => "FIRSTLIFE"}

When you have Phoenix controller, all your data send as JSON in body has keys in string format.

To prepare your code, you should use:

def new(conn, %{"invoice" => invoice_params}) do
    variable = "Hello #{invoice_params["payorcode"]} Hooray *string2 here* day" 

With map["key"] you can access parameters. Remember this will return nil when not found data in map (no data with selected key), and #{...} will replace it with "" - empty string.

1 Like

It worked. Thanks! Another question what if I no data found in map and I want it to return with "" then should I use #{["payorcode"]} like this?


Otherwise it would just print the payorcode work. :slight_smile: