Jinja

From XPUB & Lens-Based wiki

Jinja2

Jinja is one of many templating engine for Python. Although is usually used to generate HTML pages, it is not restricted. In other words, you can use Python programming structures likes lists, dictionaries, loops, conditions, etc to generate HTML pages, since often then a HTML page has a lot of fixed,unchanging elements, and some variable elements. This makes ideal for templating, by using the same template like a blueprint, and giving its variable elements different values at different times, we can save a lot of effort.

Unlike the Python modules used previously Jinja2 is not part of Python standart library, therefore we need to first install it before importing it into our scripts.

Install it with pip: sudo pip install jinja2

More on Jinja2

import jinja2

template = jinja2.Template('Hello {{ name }}!') #the simplest template with a variable:name
print 'Simple template rendered:', template.render(name='Pirate'), '\n' # render it giving a value to variable name


# templates can be more complex this for a HTML table row
row_template = jinja2.Template(''' <tr>
<td>{{library}}<td> 
<td>{{author}}<td> 
<td><a href="{{link}}">Go<td>
</tr> ''') # notice: use of ''' allows strings to be multi-line

# to fill it will use a dictionary
piratelibs = {
        'Memory_or_the_World': {'author':'Marcel Mars', 'site':'http://memoryoftheworld.org/'},
        'aaaarg': {'author':'Sea Dockray', 'site':'http://aaaaarg.fail/'},
         'Monoskop':{'author':'Dusan Barok', 'site':'http://monoskop.org/'},
         'Sci-hub': {'author':'Alexandra Elbakyan', 'site':'http://sci-hub.bz/'}
    }

# And render the template w/ the details from one piratelib

onerow = row_template.render( library='aaaarg', author=piratelibs['aaaarg']['author'], link=piratelibs['aaaarg']['site'] )
print 'row_template rendered:', onerow, '\n'


allrows=""
# what if we want to render all the pirate libs?
# then the for loop is our friend 
for lib in piratelibs.keys(): # for each entry get its key value
    #print 'key:', lib 
    #print 'value (dict):', piratelibs[lib] 
    # since the value is also a dictionary we get its values by invoking its keys: author, site
    #print piratelibs[lib]['author']
    #print piratelibs[lib]['site']
    # now we have all the elements necessary to render the template
    onerow = row_template.render( library=lib, author=piratelibs[lib]['author'], link=piratelibs[lib]['site'] )
    print onerow
        
# Challange #1: change the loops so that at each loop iteration onerow adds itself to allrows varible
# in order to get 1 large HTML string containing all row?

# Challange #2: add the content allrows in HTML template containing <!DOCTYPE html>,<html>,<body>, and <table> tag