25

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?

dreftymac
  • 31,404
  • 26
  • 119
  • 182
Clinton
  • 22,361
  • 15
  • 67
  • 163

5 Answers5

13

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.

Community
  • 1
  • 1
Paul Fioravanti
  • 16,423
  • 7
  • 71
  • 122
12

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))
zw963
  • 1,157
  • 15
  • 11
7

I was also looking for this recently for Python and stumbled upon the dynamic-yaml package, through the Awesome YAML repo on Github.

Link Awesome YAML Github Repo: https://github.com/dreftymac/awesome-yaml#parsers Link Dynamic YAML for Python: https://github.com/childsish/dynamic-yaml

Hope this helps!

Edit: Since the comments are correct and links may break, here is a simple example:

If you have a YAML file that looks like this:

house:
    street: cool_street_name
    number: 45
    street_and_number: {house.street}-{house.number}

Install dynamic_yaml with python -m pip install dynamic_yaml to run the following script.

import dynamic_yaml

with open(path_to_yaml_file, 'r') as f:
    data = dynamic_yaml.load(f)

Then you will get:

print(data['house']['street_and_number'])
>> cool_street_name-45
  • 1
    From Review: Hi, while links are great way of sharing knowledge, they won't really answer the question if they get broken in the future. Add to your answer the essential content of the link which answers the question. In case the content is too complex or too big to fit here, describe the general idea of the proposed solution. Remember to always keep a link reference to the original solution's website. See: [How do I write a good answer?](https://stackoverflow.com/help/how-to-answer) – sɐunıɔןɐqɐp Dec 20 '19 at 08:32
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.

Clinton
  • 22,361
  • 15
  • 67
  • 163
0

With Yglu, you can write your example this way:

Home: /home
Alice: !? .Home + '/alice'

or

Home: /home
Alice: !? ('{0}/alice').format($_.Home)

Disclaimer: I am the author of Yglu.

lbovet
  • 333
  • 3
  • 4