rpb
rpb

Reputation: 3299

How to efficiently update an HTML/ string dynamically in Python?

The objective is to update an HTML/ string dynamically given a list of `list_header'.

List to be inputted into the html list

list_header=['Coffee','Tea','Milk']

Predefined html template

html = """
   <tr>
       <th>List of header name:</th>
   </tr>
<ol>

</ol>
"""

Expected result

html = """
   <tr>
       <th>List of header name:</th>
   </tr>
<ol>
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ol>
"""

I tried to use the find and append approach as below, but it will omit the upper part

line = '<li> </li>'
index = line.find('</ol>')
output_line = line[:index] + list_header[0] + line[index:]

Thanks for any help in linking to good reference material.

Upvotes: 1

Views: 2122

Answers (3)

Prayson W. Daniel
Prayson W. Daniel

Reputation: 15588

You can use jinja for this kind of project. Jinja is design just to help you achieve this:

# python -m pip install —user Jinja2

from jinja2 import Template


list_headers = ['Coffee','Tea','Milk']

HTML = '''
 <tr>
       <th>List of header name:</th>
 </tr>
<ol>
{% for list_header in list_headers %}
  <li> {{ list_header }} </li>
{% endfor %}
</ol>
'''

template = Template(HTML)
res = template.render(list_headers=list_headers)

print(res)

Read more here Jinja2 to get familiar with jinja syntax.

Upvotes: 5

Rahul Kumar
Rahul Kumar

Reputation: 2345

The best would be to keep the HTML in a separate file.

<html>
    <body>
        <tr>
            <th>List of header name:</th>
        </tr>
        <ol>
            {items}
        </ol>
    </body>
</html>

Then using python script generates each items (li) in ol tag.

with open("/path/to/html", "r") as file:
    html_template = file.read()

rows = [f"<li>{item}</li>" for item in items]

html_template.format(list_items = ".".join(rows))

Upvotes: 1

ELinda
ELinda

Reputation: 2821

If you wrap the content in a root element (<html> in the example), you can use xml.etree.ElementTree.

import xml.etree.ElementTree as ET
list_header=['Coffee','Tea','Milk']

html = """<html>
<tr>
    <th>List of header name:</th>
</tr>
<ol>

</ol></html>
"""
root = ET.fromstring(html)

for inner_text in list_header:
    list_elt = ET.Element('li')
    list_elt.text = inner_text
    root[1].append(list_elt)
print(ET.tostring(root).decode("utf-8"))

Output:

<html>
<tr>
    <th>List of header name:</th>
</tr>
<ol>

<li>Coffee</li><li>Tea</li><li>Milk</li></ol></html>

Upvotes: 1

Related Questions