Reputation: 43
I am trying to print a list of items from a MySQL database onto an HTML page. My database can be added to and changed over time away from this page, so the list must change as the database changes. The trickiest part is that each of the items on the list links to a informational page (the link to the informational page would also be stored in the database). I have run all my other code in python and it runs the HTML page by doing the following:
def render_POST( self, request):
file=open('NewOptionsPage.html','r')
filedata=file.read()
return filedata
-where NewOptionsPage is my html code.
So my question is:
What do I put into my HTML code to print from my database that would also allow me to also give it a link from the database? If this isn't possible in python, how could I do it in php or another language?
Upvotes: 2
Views: 7728
Reputation: 1180
If I understand correctly, this is an excellent use-case for an HTML templating language like Jinja2 or Mako
In OptionsPage.html you might store something like:
<!DOCTYPE html>
<html lang="en">
<head>
<title>My Webpage</title>
</head>
<body>
<ul id="navigation">
{% for item in items %}
<li><a href="{{ item.href }}">{{ item.caption }}</a></li>
{% endfor %}
</ul>
<h1>My Webpage</h1>
{{ a_variable }}
{# a comment #}
</body>
</html>
Where your python code with do something like:
def get_items(db_connection):
cursor = db_connection.cursor()
cursor.execute("SELECT a, b FROM some_table")
items = cursor.fetchall()
return items
Then a little template magic:
items = get_items(db_connection)
template = Template(file='OptionsPage.html')
print(template.render(items=items, a_variable=42))
If you Google Templating languages you will see quite a few that work with python.
HTH
Upvotes: 1