Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace each instance of jinja variable with string in Python

Tags:

python

jinja2

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?

like image 934
Romit Avatar asked Sep 04 '25 16:09

Romit


2 Answers

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.

like image 56
Romit Avatar answered Sep 07 '25 16:09

Romit


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"
like image 30
Gustav Rasmussen Avatar answered Sep 07 '25 18:09

Gustav Rasmussen