Builder Examples:

Java
Java
C#
C#
PHP
PHP
Python
Python
C++
C++
TypeScript
TypeScript
▸ Builder Quick Review

A Simple HTML Builder in Python

These days, you see advertisements left and right about the newest website builder on the block. While we won't be demonstrating how to create one with very much nuance, we will be showing how the builder pattern can help get you started! This demo takes a slight spin on the usual builder pattern, in that we aren't trying to construct a complex object per-se, but a complex string that would nonetheless be cumbersome to create without the help of a builder.

The Builder:

class SimpleHtmlBuilder(object):
   def __init__(self):
       self.bodyContent = ''
   
   # Basic methods:
   def AddH1(self, text):
       self.bodyContent += '<h1>' + text + '</h1>'
   
   def AddH2(self, text):
       self.bodyContent += '<h2>' + text + '</h2>'

   def AddParagraph(self, text):
       self.bodyContent += '<p>' + text + '</p>'

   def AddHorizontalRule(self):
       self.bodyContent += '<hr>'

   def AddLineBreak(self):
       self.bodyContent += '<br>'

   # Builds the html document based on our input:
   def BuildDocument(self):
       # We'll follow the HTML 5 standard document syntax:
       return '''
       <!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Document</title>
</head>
<body>
   {}
</body>
</html>'''.format(self.bodyContent)

Demo:

htmlBuilder = SimpleHtmlBuilder()

# Create the content of the page:
htmlBuilder.AddH1("Welcome to my blog!")
htmlBuilder.AddHorizontalRule()
htmlBuilder.AddH2("What is my blog about?")
htmlBuilder.AddParagraph("Good question! I'm not so sure yet, but you can't rush creativity.")
htmlBuilder.AddLineBreak()
htmlBuilder.AddHorizontalRule()

# Build the html:
print(htmlBuilder.BuildDocument())

Challenges

  • Add functionality to create ordered, and unordered lists.
  • Refactor to allow styles, CSS classes, and even shoehorn in some JavaScript to make the webpages truly stand out.

Find any bugs in the code? let us know!