Is there an easy way to reverse transform a template?

I can do this to display the template.

>>> from django.template import Context, Template >>> t = Template("My name is {{ my_name }}.") >>> c = Context({"my_name": "Adrian"}) >>> t.render(c) u'My name is Adrian.' 

Now I would like to take the created template, and get the context from this. Sort of:

 >>> t.reverse_render('My name is Adrian.') {"my_name": "Adrian"} 

Is that even a good idea?

UPDATE: The reason I want to do this is because I get XML with a well-defined structure, and I think that retrieving data this way would be a lot easier than manually parsing XML.

I use an XML template to send a response, and I wondered if I could handle the request in the same way, but vice versa.

+4
source share
2 answers

I found a very similar way to do this without Django templates that would work well for me at the time:

 import re tmpl = 'My name is (?P<name>.*).\nI like to ride my (?P<transport>.*).' msg = 'My name is Adrian.\nI like to ride my bicycle.' print(re.compile(tmpl).match(msg).groupdict()) 

Outputs:

 {'name': 'Adrian', 'transport': 'bicycle'} 

An XML regex pattern can still be stored in an XML file and read at runtime.

0
source

As far as I know, this is not a Django feature. So no, there is no way in Django. If you have a template, you will need to create a html / xml parsing method and compare it with the template to associate each change with each {{context_label}}.

This seems like an interesting problem, but I donโ€™t see how its solution can be useful in a standard web application (thus, I see no reason why Django will have this function in the first place).

+1
source

Source: https://habr.com/ru/post/1491500/


All Articles