Giter VIP home page Giter VIP logo

htmlbuilder's Introduction

HtmlBuilder is a python library that allows you to render HTML files by writing python code. And to make use of python features, clean syntax, and object-oriented design to their full potential. (Full documentation available at readthedocs.io)

codecov python version badge

Why should you care about this library?

When rendering HTML programmatically, there are other options available (template engines and other rendering libraries). Still, these are often limited in what they can do, or it's necessary to learn a new level of abstraction before being productive. HtmlBuilder tries to improve on this by following the next few ideas:

  • Minimal learning curve: Users should need no more than Python and HTML knowledge to be productive using this tool.
  • Real python code: The final code looks and behaves as you would expect from other python code.
  • Easily testable: Users can introspect and unit test the HTML object structure before rendering the HTML string.

Installation

run pip install htmlBuilder

Use examples:

A simple example

# import necessary tags and attributes
from htmlBuilder.tags import *
from htmlBuilder.attributes import Class, Style as InlineStyle


# html tags are represented by classes 
html = Html([],
    # any tag can receive another tag as constructor parameter
    Head([],
        Title([], "A beautiful site")
    ),
    Body([Class('btn btn-success'), InlineStyle(background_color='red', bottom='35px')],
        Hr(),
        Div([],
            Div()
        )
    )
)
# no closing tags are required

# call the render() method to return tag instances as html text
print(html.render(pretty=True))

Output

    <html>
      <head>
        <title>
          A beautiful site
        </title>
      </head>
      <body class='btn btn-success' style='background-color: red; bottom: 35px'>
        <hr/>
        <div>
          <div></div>
        </div>
      </body>
    </html>

A not so simple example

from htmlBuilder.attributes import Class
from htmlBuilder.tags import Html, Head, Title, Body, Nav, Div, Footer, Ul, Li

# declare data
users = [
    {
        "name": "Jose",
        "movies": ['A beautiful mind', 'Red'],
        "favorite-number": 42,
    },
    {
        "name": "Jaime",
        "movies": ['The breakfast club', 'Fight club'],
        "favorite-number": 7,
    },
    {
        "name": "Jhon",
        "movies": ['The room', 'Yes man'],
        "favorite-number": 987654321,
    },
]


# functions can be used to handle recurring tag structures
def my_custom_nav():
    # these functions can return a tag or a list of tags ( [tag1,tag2,tag3] )
    return Nav([Class("nav pretty")],
        Div([], "A beautiful NavBar")
    )


html = Html([],
    Head([],
        Title([], "An awesome site")
    ),
    Body([],
        my_custom_nav(), # calling previously defined function
        [Div([Class(f"user-{user['name'].lower()}")],
            Div([], user['name']),
            Ul([],
                [Li([], movie) for movie in user["movies"]] # list comprehensions can be used to easily render multiple tags
            ) if user['favorite-number'] < 100 else "Favorite number is too high" # python's ternary operation is allowed too
        ) for user in users], 
        Footer([], "My Footer"),
    )
)

print(html.render(pretty=True, doctype=True)) # pass doctype=True to add a document declaration

Output

    <!DOCTYPE html>
    <html>
      <head>
        <title>
          An awesome site
        </title>
      </head>
      <body>
        <nav class='nav pretty'>
          <div>
            A beautiful NavBar
          </div>
        </nav>
        <div class='user-jose'>
          <div>
            Jose
          </div>
          <ul>
            <li>
              A beautiful mind
            </li>
            <li>
              Red
            </li>
          </ul>
        </div>
        <div class='user-jaime'>
          <div>
            Jaime
          </div>
          <ul>
            <li>
              The breakfast club
            </li>
            <li>
              Fight club
            </li>
          </ul>
        </div>
        <div class='user-jhon'>
          <div>
            Jhon
          </div>
          Favorite number is too high
        </div>
        <footer>
          My Footer
        </footer>
      </body>
    </html>

htmlbuilder's People

Contributors

jaimevp54 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

htmlbuilder's Issues

Syntax Error in tags.py

Traceback (most recent call last):
File "python_html_builder.py", line 2, in
from htmlBuilder.tags import *
File "/home/abc/.local/lib/python2.7/site-packages/htmlBuilder/tags.py", line 20
belongs_to: list = None
^
SyntaxError: invalid syntax

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.