Python for Finance: Analyze Big Financial Data

(Elle) #1
Out[78]:    ‘1, 2,  3’
In [ 79 ]: ‘{}, {}, {}’.format(*‘123’)
Out[79]: ‘1, 2, 3’

Templating to generate HTML pages works pretty similarly. The major difference is that the


string object “resembles” an HTML document (or a part thereof) and has commands for


replacements and also, for example, ways of controlling the flow when rendering the


template (e.g., the for loop). Missing information is added during the rendering


procedure, as we added the integers to the string object in the previous examples.


Consider now the following string object, containing partly standard HTML code and some


template-specific code:


In  [ 80 ]: templ   =   ”’<!doctype html>
Just print out <b>numbers</b> provided to the template.
<br><br>
{% for number in numbers %}
{{ number }}
{% endfor %}
”’

So far, this is a string object only. We have to generate a Jinja2 Template object out of it


before proceeding:


In  [ 81 ]: from jinja2 import Template
In [ 82 ]: t = Template(templ)

This Template object has a method called render to make valid HTML code out of the


template and some input values — in this case, some numbers via the parameter numbers:


In  [ 83 ]: html    =   t.render(numbers=range( 5 ))

The code is again a string object:


In  [ 84 ]: html
Out[84]: u’<!doctype html>\n Just print out <b>numbers</b> provided to the temp
late.\n <br><br>\n \n 0\n \n 1\n \n 2\n \n 3\n \n
4\n ‘

Such an object containing HTML code can be rendered in IPython Notebook as follows:


In  [ 85 ]: from IPython.display import HTML
HTML(html)
Out[85]: <IPython.core.display.HTML at 0x7fdb7e1eb890>

Of course, templating involves much more than this simple example can illustrate (e.g.,


inheritance). More details can be found at http://jinja.pocoo.org. However, the templates


for the Tradechat application already include a number of important aspects. Specifically,


we need the following templates:


layout.html

Defines the basic layout from which the other templates inherit


register.html

The template for the user registration page


login.html

The corresponding template for the user login


show_entries.html

The main page showing the comments in the chat room and, if the user is logged in,

Free download pdf