In my previous line of work, I made a living as a web developer. My time was spent building websites in content management systems, customizing the front end for clients and ensuring the back-end was usable and worked as intended. Today, I mostly tap my front-end developer experiences for building websites for use in social engineering campaigns. As we don’t use content management systems to build our sites, we’ve had to fall back on old-school techniques, which historically means lots of HTML and CSS coding to maintain decent appearances. Fortunately, Jinja2 has simplified our process significantly.
Jinga2 is a modern templating language for Python which can be used for a variety of purposes from formatting web sites to templating forms. I’ve even recently started using Jinja to templatize emails being sent through King Phisher for phishing engagements.
Jinja2
Jinja2 is an extremely powerful templating language which makes use of Python to build templates for websites. The framework was inspired by Django, so if you have experience with that kind of framework, you shouldn’t have much trouble getting into Jinja.
What makes Jinja so powerful?
Inheritance is the meat and potatoes of Jinja2, but it includes a lot of other functionality as well:
- Define and pass variables
- This includes title tags, user names, or whatever else you may need.
- Allows for defining variables from within the web page itself.
- Example:
{{ foo.bar }}
- Modify variables with use of filters
- This feature allows one to filter things such as a date or time to match current conditions, future conditions, etc.
- Allows to filter out specific things such as last 4 of a phone number.
- Sorts, removes, appends, adds items to lists
- Much more
- Example:
{{ list_foo|join(', ') }}
- Using Tests to test variables against a common expression
- Allows testing such as ‘if’ and ‘for’ loops.
- Accepts variables as well
- Example:
{% if loop.index is divisibleby 2 %}
Jinja2 has extensive documentation covering all of these features. I will also go over many of these items as this series progresses.
Inheritance
The idea of inheritance is what really Jinja2 is all about and will be one of the main points of this blog series. With inheritance, you can build a base template with a header, navigation, and a footer, then have your content pages gain all the attributes from that base template. For example:
Template File
Content Page
As you can see, this is done by adding “block” and “superblock” elements to the page which will be filled in by content defined inside other web pages which gives the structure of the website all based off of one (or more) templates.
Jinja2 is also quite useful for templating other types of files as well (XML, txt, python, etc.) making life much easier on the developer.
The next blog in the series will cover installing Jinja2 along with creating the necessary files, then getting the template and one of the pages started.