String interpolation in YAML

空扰寡人 提交于 2019-12-17 09:57:03

问题


In Perl I can do something like the following:

my $home = "/home";
my $alice = "$home/alice";

Can I do something like the following in YAML:

Home: /home
Alice: $Home/alice

So "Alice" is effectively /home/alice in the end?


回答1:


Unfortunately, you're out of luck. To do what you want you'd need to pass in $home from a view file (or wherever) and interpolate it in your yaml entry, which could possibly look something like:

Alice: ! '%{home}/Alice' 

See this StackOverflow Q&A for the detailed answer to pretty much exactly your question.




回答2:


You should use ERB template.

you can write like following:

Alice: <%=home%>/alice

When use, you need parse home value with ERB before parse as YAML. if home is local variable, you need pass local binding in as #result method's argument. if you not pass this, will use TOP LEVEL binding as default.

Like this:

require 'erb'

home = 'home'
YAML.load(ERB.new(yaml_content).result(binding))



回答3:


I ended up using YAML::AppConfig but admittedly that's not a YAML solution but a Perl specific solution. It allows for YAML to include $vars which are interpolated.



来源:https://stackoverflow.com/questions/15777987/string-interpolation-in-yaml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!