Reputation: 25
I'm trying to convert a list (from text file) to an html table code to insert in an html file. I used jinja2 succesfully to a part where I replace a keyword in html file to the html table code that I created earlier. The problem is that inside the html file all the new table tags are changed into <tr><td>
and it should be <tr><td>
etc. This is the code I use:
from bs4 import BeautifulSoup
import re
from os.path import abspath
import plistlib
from jinja2 import Template
from collections import Counter
my_plist = plistlib.readPlist("iphone_data/app_info.plist")
iphone_version = my_plist["CFBundleShortVersionString"]
changelog = open("changelog.txt", "r", encoding='utf-8')
list1 = changelog.readlines()
template = Template("""
{% for item, count in bye.items() %}
<tr><td>{{item}}</td></tr>
{% endfor %}
""")
log = template.render(bye=Counter(list1))
file = abspath('iphone_data/letter.html')
html = open(file, 'r', encoding="utf-8")
soup = BeautifulSoup(html, "html.parser")
target = soup.find_all(text=re.compile(r'wersja_1'))
changes = soup.find_all(text=re.compile(r'changelog'))
for v in target:
v.replace_with(v.replace('wersja_1', iphone_version))
for c in changes:
c.replace_with(c.replace('changelog', log))
html = soup.prettify("utf-8")
with open("iphone_data/letter_mod.html", "wb") as file:
file.write(html)
I also replace version read from plist file but that works perfect. What should the correct code look like to prevent this from happening?
Upvotes: 0
Views: 947
Reputation: 5463
There is a Flask module available just for tables: "flask_table". Documentation available here: http://flask-table.readthedocs.io/en/stable/, you can define the items in your table as an array or dictionary and process them in this way:
#load items from your database with something like
items = ItemModel.query.all()
# Populate the table
table = ItemTable(items)
# Print the html
print(table.__html__())
# or just {{ table }} from within a Jinja template
Upvotes: 0