Reputation: 27
I am outputting an HTML file in Python. Inside the HTML, I have a table showing the keys and values from the dictionary in the Python file and I think I have to use a loop to display the table data in this case. But I'm confused about using python to output html content. I have tried using<% %> which is supposed to allow Python code in HTML but it didn't work..
message = """
<html>
<body>
<h1>Counting words</h1>
<table border = 1>
<tr>
<th>Words</th>
<th>Count</th>
</tr>
<% for key, value in wordDict.items(): %>
<% if value >= 10: %>
<tr>
<td><% print(key) %></td>
<td><% print(value) %></td>
</tr>
<% end %>
<% end %>
</table>
</body>
</html>"""
f.write(message)
f.close()
Upvotes: 0
Views: 2134
Reputation: 47364
You can use string formatting to insert dynamic values into string:
message = """
<html>
<body>
<h1>Counting words</h1>
<table border = 1>
<tr>
<th>Words</th>
<th>Count</th>
</tr>
{0}
</table>
</body>
</html>"""
wordDict = {1: 'a', 2: 'b', 3: 'c'}
insert = []
for k, v in wordDict.items():
insert.append("<tr><td>{0}</td><td>{1}</td></tr>".format(k, v))
print(message.format(''.join(insert)))
output:
<html>
<body>
<h1>Counting words</h1>
<table border = 1>
<tr>
<th>Words</th>
<th>Count</th>
</tr>
<tr><td>1</td><td>a</td></tr><tr><td>2</td><td>b</td></tr><tr><td>3</td><td>c</td></tr>
</table>
</body>
</html>
Upvotes: 3
Reputation: 116
You have a syntax error. When using Joomla, you have to have finishing tags which look like this: <% endfor %> and <% endif %> and I am not sure abou the : after the for loop, try this if it's not workinng, play around with it
message = """
<html>
<body>
<h1>Counting words</h1>
<table border = 1>
<tr>
<th>Words</th>
<th>Count</th>
</tr>
<% for key, value in wordDict.items() %>
<% if value >= 10 %>
<tr>
<td><% print(key) %></td>
<td><% print(value) %></td>
</tr>
<% endif %>
<% endfor %>
</table>
</body>
</html>"""
f.write(message)
f.close()
Upvotes: 0