How to read config variable in Phoenix / Elixir?

ElixirPhoenix Framework

Elixir Problem Overview


I'd like to set the title of my app in my/config/config.exs file:

config :my, My.Endpoint,
  url: [host: "localhost"],
  root: Path.dirname(__DIR__),
  secret_key_base: "secret",
  title: "My App"

How can I read title later to use it in template? Something like:

<div>
  Title of my app is <%= ??? %>
</div>

I tried conn.title and it says there's no such key. But, when I try conn.secret_key_base it works. Why?

Elixir Solutions


Solution 1 - Elixir

The get_env function is part of the Application module from the Elixir/Erlang core.

This function returns the value for a specific key in the app's environment. Considering your configuration, you would access the title property this way:

Application.get_env(:my, My.Endpoint)[:title]

The third parameter is for passing a default value when the config key doesn't exist.

Solution 2 - Elixir

You may use Application.get_env(:my, :title)

Solution 3 - Elixir

Let's say in dev.ex file you have a config variables

config :app_name, AppName.Endpoint,
  api_prefix: "api/v2",
  api_host: "http://0.0.0.0",
  api_port: "3000"

You can fetch all three config variables

Application.get_env(:app_name, AppName.Endpoint)[:api_prefix]
Application.get_env(:app_name, AppName.Endpoint)[:api_host]
Application.get_env(:app_name, AppName.Endpoint)[:api_port] 

Solution 4 - Elixir

To have clear separation between my custom configuration and configuration for phoenix and other modules I used:

config :ace, :config,
  root: Path.dirname(__DIR__),
  title: "Ace"

And then you retrieve the value using a get_env call like:

iex> Application.get_env(:ace, :config)[:title]
"Ace" 

Solution 5 - Elixir

if you look under the hood how the config is just a function that add config values to a keyword list and later you can access them in your app

config/2 takes a key and maps it to keyword_list, config/3 takes a key and adds key with keyword_list as value.

Since you are using config/3 it namesapces your config under My.Endpoint this would work Application.get_env(:my, My.Endpoint, :title)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlex CraftView Question on Stackoverflow
Solution 1 - ElixirTiago EngelView Answer on Stackoverflow
Solution 2 - ElixirSasha FonsecaView Answer on Stackoverflow
Solution 3 - ElixirJagdishView Answer on Stackoverflow
Solution 4 - ElixiriheggieView Answer on Stackoverflow
Solution 5 - ElixirallyrazaView Answer on Stackoverflow