String.format conflcits with css tags: {}

This is how I replace the variables in my html templates

a1 = '<html><title>{0}</title><body>{1}</body></html>' vars = ['test', 'test'] output = a1.format(*vars) 

the problem is .. this conflicts with css tags when there is css in html.

because css contains:

  {}'s 
+6
source share
3 answers

An alternative approach.

Since you have a combination of HTML and Python code, I would suggest to separate the logical part and the part of the presentation , switching to the usual template engine .

An example of using mako .

Create an HTML template file, leaving the appropriate placeholders:

 <html> <head> <title>${title}</title> </head> <body> <p>${text}</p> </body> </html> 

Then, in python code, render the template containing the values ​​for placehodlers:

 from mako.template import Template t = Template(filename='index.html') print t.render(title='My Title', text='My Text') 

This will print:

 <html> <head> <title>My Title</title> </head> <body> <p>My Text</p> </body> </html> 
+4
source

Just use double curly braces to avoid them.

like

 a1 = """div.test{{ bla; }}""" 
+1
source

You can use templates, as Alex said, or use formatting with a dictionary

 a1 = '<html><title>%(title)s</title><body>%(body)s</body></html>' vars = {'title': 'test', 'body': 'test'} output = a1 % vars 
0
source

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


All Articles