Create a jinja2 template from a nested dictionary with string representation of Jinja2 variables as values

Viewed 26

I have a dictionary on the following format

 {'n11' : 
        {'n12a':
               {'n13a' : '{{n11_n12a_n13a}}' , 'n13b' : '{{n11_n12a_n13b}}'},
         'n12b':
                {'n13c' : 
                          {'n14a': '{{n11_n12b_n13c_n14a}}'}
                }
         },
   'n21': 
         {'n22a' : '{{n21_n22a}}' }
 }

And I want to, based on this, generate a YAML template that looks like

n11 : 
      n12a:
            n13a: {{n11_n12a_n13a}}
            n13b: {{n11_n12a_n13b}}
      n12b: 
            n13c:
                  n14a: {{n11_n12b_n13c_n14a}}
n21 :
      n22a: {{n21_n22a}}

If I just dump the dictionary

import yaml

ff = open('./dictionary_to_template.yaml', 'w+')

yaml.dump(dictionary, ff, allow_unicode=True)

it will still keep the string quotes.

n11 : 
      n12a:
            n13a: "{{n11_n12a_n13a}}"
            n13b: "{{n11_n12a_n13b}}"
      n12b: 
            n13c:
                  n14a: "{{n11_n12b_n13c_n14a}}"
n21 :
      n22a: "{{n21_n22a}}"

So is there a way to remove the string quotes when I create the YAML file so that it becomes proper Jinja2 variables?

EDIT:

code to generate dictionary

  d = {'n11' : {'n12a': {'n13a' : '{{n11_n12a_n13a}}' , 'n13b' : '{{n11_n12a_n13b}}'}, 'n12b': {'n13c' :  {'n14a': '{{n11_n12b_n13c_n14a}}' }}, 'n21': {'n22a' : '{{n21_n22a}}' }}}
1 Answers

You can work around with this technique

   d = {'n11' : 
        {'n12a':
               {'n13a' : {} , 'n13b' : {} },
         'n12b':
                {'n13c' : 
                          {'n14a': {}}
                }
         },
   'n21': 
         {'n22a' : {} }
 }
# while creating the above dictionary you can store all jinja template value in list

import yaml
ff = open('./dictionary_to_template.yaml', 'w+')
li_in_order = ["{{n11_n12a_n13a}}",'{{n11_n12a_n13b}}','{{n11_n12b_n13c_n14a}}','{{n21_n22a}}']
print(yaml.dump(d, allow_unicode=True).format(*li_in_order), file=ff)
ff.close()
Related