Mr T. Mr T. - 2 months ago 7
Python Question

multiple text replacements in string by markers

I have an xml file that is used as a template.
I have multiple markers inside this xml that will be replaced with actual data. This is what i did:


def populate_template(self, value1, value2, value3):
with open('my_template.xml', 'rb') as xml_template:
template_string = xml_template.read()

template_string.replace('{{MARKER_1}}', value1)
template_string.replace('{{MARKER_2}}', value2)
template_string.replace('{{MARKER_3}}', value3)
return template_string


Each marker can appear multiple times inside the template.

I was wondering if there is a more efficient way of doing this?

Tech stuff:


  • Python 2.7


Answer

Yes. Use the jinja2 templating module. To use your existing template you could do something like this:

def populate_template(self, value1, value2, value3):
    from jinja2 import Template
    t = Template(open('my_template.xml', 'r').read())
    output = t.render(MARKER_1=value2, MARKER_2=value2, MARKER_3=value3)
    return output

It's well worth studying the different ways you can pass arguments to the template, also. For example the same code could have been written as...

    ...
    context = {'MARKER_1': value1, 'MARKER_2', value2, 'MARKER_3': value3}
    output = t.render(**context)

and you can use this trick with any old dicts you happen to have lying around. It's a great way of extracting readable information from dicts selectively.

The designers of jinja2, being smart cookies sympathetic to the Python cause, have in fact helped you by allowing you to provide the context in any of the ways you can create a dict (keyword arguments, a list of (key, value) tuples or a dict - including other dict-like things such as collections.OrderedDict). So you could also write the second line as

    output = t.render(context)

which is both more readable and more efficient (I'm guessing, but it's an informed guess).

Comments