Let's say you have a text string that greets a person, 'Hello, Mark!'
.
If you write a program for this greeting you might want to compose the string for any name of the person.
One way to do this is to have a template string, 'Hello, ${user_name}!'
and then use a function that will
replace the ${...}
with value of variable user_name
. This is usually called string interpolation.
We want to have a dict interpolation, where the same is done for a nested structure.
For example, if you have a dictionary, {'user':'User_id${uid}'}
, and a variable uid=1
, we want to get
dictionary {'user':'User_id1'}
.
This is already built into python for strings.
https://docs.python.org/3/library/string.html#template-strings
>>> from string import Template
>>> s = Template('$who likes $what')
>>> s.substitute(who='tim', what='kung pao')
'tim likes kung pao'
- chevron (mustache)
- Jinja
- and a lot more
- Template - string(dict?) that specifies the structure of resulting object.
- Variables - variables to put into Template
Suppose that you have a Template provided by some user you don't know. He also could be a hacker. You have to write a function that takes
- a json-serializable template
- dictionary of variables and interpolates them. After that it parses the json and returns dict
You may use any template format language
- Readability
- Will this code work for lists?
- What if variable itself is a dict?
template = '{"post":"$post_data"},
variables = {'post_data':{"text":"hello","user":"Mark"}}
- What if variable itself has a JSON object?
template = '{"post":"$post_data"},
variables = {'post_data':'{"text":"hello","user":"Mark"}'}
- What if our Template is dict, not string?
- First read the docs and other solutions
- Think before writing
- After you think you understand how to do, describe it and send the description to me.
- If you have any, even the most stupid in the world question - ask me.