Skip to content

Instantly share code, notes, and snippets.

@rjsnh1522
Last active May 8, 2020 10:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rjsnh1522/3f76cfba788b5abfd3e1357030ab2013 to your computer and use it in GitHub Desktop.
Save rjsnh1522/3f76cfba788b5abfd3e1357030ab2013 to your computer and use it in GitHub Desktop.
Adding custom filter to all variables in jinja2
from jinja2.lexer import Token
from jinja2.ext import Extension
class ListDictTable(Extension):
tags = set(['listdicttable'])
def filter_stream(self, stream):
variable_done = False
in_trans = False
in_variable = False
for token in stream:
# Check if we are inside a trans block - we cannot use filters there!
if token.type == 'block_begin':
block_name = stream.current.value
if block_name == 'trans':
in_trans = True
elif block_name == 'endtrans':
in_trans = False
elif token.type == 'variable_begin':
in_variable = True
if not in_trans and in_variable:
if token.type == 'pipe':
# Inject our filter call before the first filter
yield Token(token.lineno, 'pipe', '|')
yield Token(token.lineno, 'name', 'list_dict_to_table_filter')
variable_done = True
elif token.type == 'variable_end' or (token.type == 'name' and token.value == 'if'):
if not variable_done:
# Inject our filter call if we haven't injected it right after the variable
yield Token(token.lineno, 'pipe', '|')
yield Token(token.lineno, 'name', 'list_dict_to_table_filter')
variable_done = False
if token.type == 'variable_end':
in_variable = False
# Original token
yield token
from json2html import *
from bs4 import BeautifulSoup
def list_dict_to_table_filter(input):
table_attributes = "class='info-table'"
if isinstance(input, list):
first = input[0]
if isinstance(first, dict):
input = {'sample': input}
data = json2html.convert(json=input, encode=False, table_attributes=table_attributes)
soup = BeautifulSoup(data, features="html.parser")
tables = soup.find('table', class_='info-table')
data = tables.find_all('table')[0]
else:
data = input
else:
data = input
return data
import jinja2
from jinja2 import Environment
from extension import ListDictTable
from filters import list_dict_to_table_filter
data = [
{
'a': 124,
'b': 2342,
'c': 999
},
{
'a': 000,
'b': 777,
'c': 989
},
{
'a': 676,
'b': 453,
'c': 321
},
{
'a': 654,
'b': 975,
'c': 543,
}
]
def main():
env = Environment(extensions=[ListDictTable])
env.filters['list_dict_to_table_filter'] = list_dict_to_table_filter
template = env.from_string("{{ data }}")
print(template.render(data=data))
if __name__ == '__main__':
main()
Jinja2==2.11.2
json2html==1.3.0
MarkupSafe==1.1.1
bs4==0.0.1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment