salsbury
salsbury

Reputation: 2803

Trouble getting config values within Phoenix controller and/or template

I'm trying to get a value from a Phoenix config file in a controller.

# config.exs

use Mix.Config

config :app_name, AppName.Endpoint,
  url: [host: "localhost"],
  debug_errors: false,
  root: Path.expand("..", __DIR__)

Application.get_env(:app_name, :url), for example, seems to return nothing.

Am I missing something?

Upvotes: 13

Views: 1912

Answers (1)

whatyouhide
whatyouhide

Reputation: 16781

As you can see in the docs for the Mix.Config module, there are two variants of config: config/2 and config/3. You are using the config/3 variant as you're passing three arguments:

  • :app_name
  • AppName.Endpoint
  • a keyword list ([url: ..., debug_errors: ...])

This means that you're configuring the AppName.Endpoint key in the environment of the :app_name application, and setting its value to the keyword list (remember AppName.Endpoint is just an atom, so it's fine to use it as a key). To retrieve the url, you would need to do something like:

Application.get_env(:app_name, AppName.Endpoint)[:url]

For the sake of completeness, config/2 allows to set multiple key-value pairs in the env for an application. Its arguments are, in fact, the application name and a list of key-value pairs.

Upvotes: 19

Related Questions