Skip to content

Instantly share code, notes, and snippets.

@adzhurinskij
Created April 25, 2017 11:58
Show Gist options
  • Save adzhurinskij/cebf7e3c5b5c8c75075fba21d7222e4d to your computer and use it in GitHub Desktop.
Save adzhurinskij/cebf7e3c5b5c8c75075fba21d7222e4d to your computer and use it in GitHub Desktop.
How to create custom filters in Jinja2
# -*- coding: utf-8 -*-
from wsgiref.simple_server import make_server
from jinja2 import Environment, FileSystemLoader
import time
import sys
# Change default encoding to UTF-8
# We need to reload sys module first, because setdefaultencoding is available
# only at startup time
reload(sys)
sys.setdefaultencoding('utf-8')
env = Environment(loader=FileSystemLoader('/var/www/static'))
# Filters are functions that are used to convert a value to some other format
# In this example, we're taking an Unix timestamp (number of seconds since 1970)
# and we're converting it to one of the two date/time formats
def format_date_EU(unix_timestamp):
return time.strftime('%d-%m-%Y, %H:%M', time.localtime(unix_timestamp))
def format_date_US(unix_timestamp):
return time.strftime('%m/%d/%Y, %I:%M %p', time.localtime(unix_timestamp))
# Adding filters to enviroment to make them visible in the template
env.filters['format_date_EU'] = format_date_EU
env.filters['format_date_US'] = format_date_US
# Load template from file
template = env.get_template('index.html')
# WSGI function that handles HTTP requests to our application
def application(environ, start_response):
start_response('200 OK', [('Content-type', 'text/html; charset=utf-8')])
# Passing arguments ("date" variable), rendering the template
#
# WSGI applications should return an iterable object
# in this example we use a list of one string
return [template.render(date=time.time()).encode('utf-8')]
# If you want to run a standalone HTTP server
# instead of configuring a WSGI proxy (for instance Apache)...
if __name__ == '__main__':
httpd = make_server('', 8000, application)
httpd.serve_forever()
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Custom filters - Jinja2</title>
<style type="text/css">
.main{
height: 300px;
width: 600px;
background-color: #33b5e5;
margin: auto;
text-align: center;
vertical-align: middle;
font-size: 200%;
border: 1px solid;
display: table-cell;
}
.wrapper{
margin: auto;
width: 602px;
}
</style>
</head>
<body style="background-color: #47473c; color: white; width= 100%;">
<div class="wrapper">
<div class="main">
{# formating date using our custom filters #}
<p> Date(US format): {{ date | format_date_US }} </p>
<p> Date(EU format): {{ date | format_date_EU }} </p>
</div>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment