如何从Phoenix的环境文件中获取变量值? [英] How to get a variable value from Environment files in Phoenix?
问题描述
我正在部署我的第一个Phoenix应用程序,并且已经在我的环境文件(dev.exs
和prod.exs
)中指定了变量的值.
I'm deploying my first Phoenix Application, and I've specified the values of a variable in my Environment Files (dev.exs
and prod.exs
).
现在,我正在尝试弄清楚如何在我的控制器中访问它们.
Now I'm trying to figure out how to access them in my Controllers.
# config/dev.exs
config :my_app, MyApp.Endpoint,
http: [port: 4000],
debug_errors: true,
cache_static_lookup: false,
my_var: "DEVELOPMENT VALUE"
# config/prod.exs
config :my_app, MyApp.Endpoint,
http: [port: {:system, "PORT"}],
url: [host: "example.com"],
my_var: "PRODUCTION VALUE"
推荐答案
好的,发现了一些东西. 长生不老药 Application.get_env/3
是必经之路:
Okay, found something. Elixir's Application.get_env/3
is the way to go:
get_env(app, key, default \\ nil)
但是问题在于,对于当前情况,accessor命令变得很长:
But the problem with this is that the accessor command becomes very long for the current situation:
# Set value in config/some_env_file.exs
config :my_large_app_name, MyLargeAppName.Endpoint,
http: [port: {:system, "PORT"}],
url: [host: "example.com"],
my_var: "MY ENV VARIABLE"
# Get it back
Application.get_env(:my_large_app_name, MyLargeAppName.Endpoint)[:my_var]
一种更好的方法 是在单独的部分中对其进行定义:
A better way would be to define them in a separate section:
config :app_vars,
a_string: "Some String",
some_list: [a: 1, b: 2, c: 3],
another_bool: true
并像这样访问它们:
Application.get_env(:app_vars, :a_string)
# => "Some String"
或者您可以获取所有键值对的list
:
Or you could fetch a list
of all key-value pairs:
Application.get_all_env(:app_vars)
# => [a_string: "Some String", some_list: [a: 1, b: 2, c: 3], another_bool: true]
这篇关于如何从Phoenix的环境文件中获取变量值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!