Are variables within YAML files possible? For example:
theme: name: default css_path: compiled/themes/$theme.name layout_path: themes/$theme.name
In this example, how can theme: name: default
be used in other settings? What is the syntax?
YAML example¶ We can use the ampersand & character to create a named anchor, that we can then reference later on with an asterisk *. Anchor names must not contain the [, ], {, } and , characters.
If a value after a colon starts with a “{”, YAML will think it is a dictionary, so you must quote it, like so: foo: "{{ variable }}" If your value starts with a quote the entire value must be quoted, not just part of it.
yml has more pages than . yaml " are not arguments, they are just statistics about the popularity of project(s) that have it wrong or right (with regards to the extension of YAML files). You can try to prove that some projects are popular, just because they use a . yml extension instead of the correct .
I had this same question, and after a lot of research, it looks like it's not possible.
The answer from cgat is on the right track, but you can't actually concatenate references like that.
Here are things you can do with "variables" in YAML (which are officially called "node anchors" when you set them and "references" when you use them later):
default: &default_title This Post Has No Title title: *default_title
{ or }
example_post: &example title: My mom likes roosters body: Seriously, she does. And I don't know when it started. date: 8/18/2012 first_post: *example second_post: title: whatever, etc.
For more info, see this section of the wiki page about YAML: http://en.wikipedia.org/wiki/YAML#References
default: &DEFAULT URL: stooges.com throw_pies?: true stooges: &stooge_list larry: first_stooge moe: second_stooge curly: third_stooge development: <<: *DEFAULT URL: stooges.local stooges: shemp: fourth_stooge test: <<: *DEFAULT URL: test.stooges.qa stooges: <<: *stooge_list shemp: fourth_stooge
This is taken directly from a great demo here: https://gist.github.com/bowsersenior/979804
After some search, I've found a cleaner solution wich use the %
operator.
In your YAML file :
key : 'This is the foobar var : %{foobar}'
In your ruby code :
require 'yaml' file = YAML.load_file('your_file.yml') foobar = 'Hello World !' content = file['key'] modified_content = content % { :foobar => foobar } puts modified_content
And the output is :
This is the foobar var : Hello World !
As @jschorr said in the comment, you can also add multiple variable to the value in the Yaml file :
Yaml :
key : 'The foo var is %{foo} and the bar var is %{bar} !'
Ruby :
# ... foo = 'FOO' bar = 'BAR' # ... modified_content = content % { :foo => foo, :bar => bar }
Output :
The foo var is FOO and the bar var is BAR !
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With