I have the following code to create a string using Jinja
from jinja2 import Template
jT = Template('"text": {{text}}, "peripherals": {{peripherals}}')
params = {'text': 'some_text', 'peripherals': 'mouse'}
jT.render(**params)
The resulting output is:
'"text": some_text, "peripherals": mouse'
Is there a way to surround the substituted values inside quotes, like so:
'"text": "hello", "peripherals": "mouse"'
Besides editing the existing jinja and using {{text|tojson}}, is there a way/function in Python to automatically wrap every substituted value inside quotes?
If the Jinja package doesn't have a built-in tool to replace each variable automatically with strings, then I think this would be the right approach:
import re
from jinja2 import Template
template = '{"text": {{text}}, "peripherals": {{peripherals}}}'
# Use regular expressions to identify the variables
template = re.sub(r"({{)(\w*)(}})", r'"\1\2\3"', template)
jT = Template(template)
params = {'text': 'some_text', 'peripherals': 'mouse'}
print(jT.render(**params))
It simply searches for the variables in the template and encapsulates them inside quotes.
Just modify your template:
from jinja2 import Template
jT = Template('"text": "{{text}}", "peripherals": "{{peripherals}}"')
params = {'text': 'some_text', 'peripherals': 'mouse'}
print(jT.render(**params))
Returns:
"text": "some_text", "peripherals": "mouse"
Without modifying the template, use this custom code:
jT = Template('"text": {{text}}, "peripherals": {{peripherals}}')
params = {'text': 'some_text', 'peripherals': 'mouse'}
j = jT.render(**params)
# Specifically for your example:
print(f'{j.split()[0]} "{j.split()[1][:-1]}", {j.split()[2]} "{j.split()[3]}"')
# More general:
for i in range(len(j.split()) - 1):
if i % 2 == 0:
print(j.split()[i] + ' ', end='')
else:
print('"' + j.split()[i][:-1] + '",', end=' ')
print('"' + j.split()[-1] + '"')
Returns:
"text": "some_text", "peripherals": "mouse"
"text": "some_text", "peripherals": "mouse"
Put it in a function if you need to run it for multiple templates:
def render_template(j):
for i in range(len(j.split()) - 1):
if i % 2 == 0:
print(j.split()[i] + ' ', end='')
else:
print('"' + j.split()[i][:-1] + '",', end=' ')
print('"' + j.split()[-1] + '"')
render_template(j)
Again returns:
"text": "some_text", "peripherals": "mouse"
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