6 Methods to Convert YAML to HTML in Python

This tutorial explores various Python libraries and methods to transform YAML data into HTML.

We’ll cover multiple methods, from template engines like Mako and Mustache to HTML generation libraries like Yattag and Dominate.

 

 

Using Mako

You can use the Mako template engine to transform YAML data into HTML templates seamlessly.

from mako.template import Template
import yaml
yaml_data = """
employees:
  - name: Ahmed
    role: Developer
  - name: Layla
    role: Designer
"""
data = yaml.safe_load(yaml_data)
html_template = """
<html>
<head><title>Employees</title></head>
<body>
    <h1>Employee List</h1>
    <ul>
    % for employee in employees:
        <li>${employee['name']} - ${employee['role']}</li>
    % endfor
    </ul>
</body>
</html>
"""
template = Template(html_template)
html_output = template.render(employees=data['employees'])
print(html_output)

Output:

<html>
<head><title>Employees</title></head>
<body>
    <h1>Employee List</h1>
    <ul>
        <li>Ahmed - Developer</li>
        <li>Layla - Designer</li>
    </ul>
</body>
</html>

 

Using Mustache with Pystache

You can use Pystache, a Mustache templating library to convert YAML data into HTML with minimal setup.

import pystache
import yaml
yaml_data = """
projects:
  - title: Website Redesign
    manager: Omar
  - title: Mobile App
    manager: Sara
"""
data = yaml.safe_load(yaml_data)
template = """
<h2>Projects</h2>
<ul>
{{#projects}}
    <li>{{title}} managed by {{manager}}</li>
{{/projects}}
</ul>
"""
html_output = pystache.render(template, data)
print(html_output)

Output:

<h2>Projects</h2>
<ul>
    <li>Website Redesign managed by Omar</li>
    <li>Mobile App managed by Sara</li>
</ul>

 

Using Yattag

You can use Yattag to build HTML documents dynamically from YAML data with a straightforward API.

from yattag import Doc
import yaml
yaml_data = """
team:
  leader: Nadia
  members:
    - name: Karim
      role: Tester
    - name: Mona
      role: Support
"""
data = yaml.safe_load(yaml_data)
doc, tag, text = Doc().tagtext()
with tag('h1'):
    text('Team Information')
with tag('p'):
    text(f"Leader: {data['team']['leader']}")
with tag('ul'):
    for member in data['team']['members']:
        with tag('li'):
            text(f"{member['name']} - {member['role']}")
html_output = doc.getvalue()
print(html_output)

Output:

<h1>Team Information</h1><p>Leader: Nadia</p><ul><li>Karim - Tester</li><li>Mona - Support</li></ul>

 

Using Dominate

You can use Dominate to generate HTML from YAML data with Pythonic syntax.

import dominate
from dominate.tags import *
import yaml
yaml_data = """
library:
  name: Cairo Library
  books:
    - title: Python Programming
      author: Youssef
    - title: Data Structures
      author: Amina
"""
data = yaml.safe_load(yaml_data)
doc = dominate.document(title='Library Catalog')
with doc.head:
    title('Library Catalog')
with doc:
    h1('Library Name')
    p(data['library']['name'])
    h2('Available Books')
    with ul():
        for book in data['library']['books']:
            li(f"{book['title']} by {book['author']}")
print(doc)

Output:

<!DOCTYPE html>
<html>
  <head>
    <title>Library Catalog</title>
    <title>Library Catalog</title>
  </head>
  <body>
    <h1>Library Name</h1>
    <p>Cairo Library</p>
    <h2>Available Books</h2>
    <ul>
      <li>Python Programming by Youssef</li>
      <li>Data Structures by Amina</li>
    </ul>
  </body>
</html>

 

Using Python string.Template

You can use Python built-in string.Template to interpolate YAML data into HTML templates.

from string import Template
import yaml
yaml_data = """
courses:
  - name: Web Development
    instructor: Hani
  - name: Machine Learning
    instructor: Dina
"""
data = yaml.safe_load(yaml_data)
template_str = """
<h1>Course Offerings</h1>
<ul>
% for course in courses:
    <li>${name} taught by ${instructor}</li>
% endfor
</ul>
"""

html_courses = ''.join([f"<li>{course['name']} taught by {course['instructor']}</li>" for course in data['courses']])
template = Template("""
<h1>Course Offerings</h1>
<ul>
$courses
</ul>
""")
html_output = template.substitute(courses=html_courses)
print(html_output)

Output:

<h1>Course Offerings</h1>
<ul>
<li>Web Development taught by Hani</li><li>Machine Learning taught by Dina</li>
</ul>

The courses from YAML are inserted into an HTML list using string.Template for substitution.

 

Using PyYAML with lxml

You can combine PyYAML with lxml to parse YAML data and construct HTML documents programmatically.

from lxml import etree
data = {
  'portfolio': {
      'client': "Tech Corp",
      'projects': [
          {'name': "AI Integration", 'status': "Completed"},
          {'name': "Cloud Migration", 'status': "In Progress"}
      ]
  }
}
root = etree.Element('html')
head = etree.SubElement(root, 'head')
title = etree.SubElement(head, 'title')
title.text = 'Portfolio'
body = etree.SubElement(root, 'body')
h1 = etree.SubElement(body, 'h1')
h1.text = 'Client Portfolio'
client_p = etree.SubElement(body, 'p')
client_p.text = f"Client: {data['portfolio']['client']}"
h2 = etree.SubElement(body, 'h2')
h2.text = 'Projects'
ul = etree.SubElement(body, 'ul')
for project in data['portfolio']['projects']:
  li = etree.SubElement(ul, 'li')
  li.text = f"{project['name']} - {project['status']}"
html_output = etree.tostring(root, pretty_print=True, doctype='').decode()
print(html_output)

Output:

<!DOCTYPE html>
<html>
  <head>
    <title>Portfolio</title>
  </head>
  <body>
    <h1>Client Portfolio</h1>
    <p>Client: Tech Corp</p>
    <h2>Projects</h2>
    <ul>
      <li>AI Integration - Completed</li>
      <li>Cloud Migration - In Progress</li>
    </ul>
  </body>
</html>
Leave a Reply

Your email address will not be published. Required fields are marked *