Showing posts with label Jinja2. Show all posts
Showing posts with label Jinja2. Show all posts

2014/02/26

Jinja2 template engine, simple basics.

Template engines will allow you to keep your HTML code outside of your code base. Managing and generating HTML in code is a bad practise. Templates will also give nice boost for performance and give you more secure system. this naturally depends how you are using your templates.

This is what Jinja2 is hyping in their features list:


  • Sandboxed execution
  • Powerful automatic HTML escaping system for XSS prevention
  • Template inheritance
  • Compiles down to the optimal python code just in time
  • Optional ahead of time template compilation
  • Easy to debug. Line numbers of exceptions directly point to the correct line in the template.
  • Configurable syntax

  • I was surprised to see how flexible Jinja2 for instance is. Variables can be modifier by filters you can see the full list of built in filters from here: http://jinja.pocoo.org/docs/templates/#builtin-filters

    Here is some basics, which are usually enough to get going.

    I'm passing this test data to Jinja2 (I'm using Python):

     template_data = {"page_title": "Testing templating",  
                      "page_text": "This is my Jinja2 rendered web page!",  
                      "loop_data": ["item1", "item2", "item3"]}  
    

    Data is in dict format. It consists title, text and some data for demonstrating looping. Loop data is placed inside a list.

    This is my template file:

     <html>  
     <head>  
     <title>{{ page_title }}</title>  
     </head>  
     <body>  
     <h1>{{ page_text }}</h1>  
     Loop data:  
     {% for row in loop_data %}  
      {% if row == "item2" %}  
       <font color="red">{{ row }}</font>  
      {% else %}  
       {{ row }}  
      {% endif %}}  
     {% endfor %}  
     </body>  
     </html>  
    

    Variables are referred with {{ var_name }}.

    For loop works like in any other programming language. Just loop list named loop_data and represent its data with variable row in the loop.

    There is also a example how simple IF works. Basically when row value hits "item2" in the loop, font color should be in red. You can also specify {% elif %} blocks.