Use YAML with variables

前端 未结 5 1015
你的背包
你的背包 2020-11-28 22:47

Are variables within YAML files possible? For example:

theme:
  name: default
  css_path: compiled/themes/$theme.name
  layout_path: themes/$theme.name
         


        
5条回答
  •  萌比男神i
    2020-11-28 23:04

    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 !
    

提交回复
热议问题