This is the way i replace 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 the html.
because css contains:
{}'s
Alternative approach.
Since you have a mix of HTML and Python code, I would suggest to separate the logic part and the presentation part by switching to a normal template engine.
Example using mako
.
Create a template HTML file leaving appropriate "placeholders":
<html>
<head>
<title>${title}</title>
</head>
<body>
<p>${text}</p>
</body>
</html>
Then, in the python code, render the template providing the values for placehodlers:
from mako.template import Template
t = Template(filename='index.html')
print t.render(title='My Title', text='My Text')
This would print:
<html>
<head>
<title>My Title</title>
</head>
<body>
<p>My Text</p>
</body>
</html>
Just use double braces to escape them.
like,
a1 = """div.test{{
bla;
}}"""
There are several good answers to this question, but they may not be appropriate in every circumstance.
Use a Template Engine: this is a great way to solve the OP's problem, but it may not always possible to install and import a non-standard library like mako
in every environment.
Escaping braces {
with double braces {{
: this may be honored in some browsers but not others (it probably should be honored, but may not be).
Another option when generating html on the fly or bringing it in from a file is to simply manage the order of how the html output is constructed--perform the CSS injection after the format operation.
my_html = """<html>
<head>
<title>My Page</title>
<style></style>
</head>
<body>
<p>Content = {0}</p>
</body>
</html>"""
my_css = """<style>
body {
background-color: gray;
}
</style>"""
my_page = my_html.format('foobar')
my_final_page = my_page.replace('<style></style>', my_css)
<html>
<head>
<title>My Page</title>
<style>
body {
background-color: gray;
}
</style>
</head>
<body>
<p>Content = foobar</p>
</body>
</html>
You don't have to use the <style></style>
tag pair as the placeholder. The placeholder could be just about anything as long as it's unique (so you don't inadvertently replace something else, too).
#! /usr/bin/env python
# -*- coding: utf-8 -*-
my_html = """<html>
<head>
<title>My Page</title>
<style></style>
</head>
<body>
<p>Content = {0}</p>
</body>
</html>"""
my_css = """<style>
body {
background-color: gray;
}
</style>"""
my_page = my_html.format('foobar')
my_final_page = my_page.replace('<style></style>', my_css)
print(my_final_page)
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