Created
September 11, 2012 12:50
-
-
Save Christophe31/3698212 to your computer and use it in GitHub Desktop.
jinja2_rtf_ugly
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
""" | |
usage: | |
from jinja_env import template_from_rtf | |
template = template_from_rtf(open("my.rtf", 'rb').read()) | |
context = {"var1":5, "now":datetime.datetime.now()} | |
template.render(**context) | |
note: special opening and closing braces and ";" for required spaces | |
exemple: | |
[[%if;var1%]][[#now|date#]][[%endif%]] | |
rqe: all "{", "}", "\", ";" will be stripped so [[#"{};;\"#]] will have an undetermined behaviour | |
""" | |
import jinja2 | |
logic_braces = ("[[%", "%]]") | |
insert_braces = ("[[#", "#]]") | |
jinja_env = jinja2.Environment(logic_braces[0], logic_braces[1], | |
insert_braces[0], insert_braces[1], | |
"<<<#", "#>>>") | |
def render_date(value, format="court"): | |
if format == 'long': | |
format = "%d/%m/%Y à %H:%M" | |
elif format == 'court': | |
format = "%d/%m/%Y" | |
return value.strftime(format) | |
def rtf_accents(value): | |
text = "" | |
value = unicode(value) | |
for unichar in value: | |
point = ord(unichar) | |
if point < 128: | |
text += str(unichar) | |
else: | |
text += br'\u%d?' % point | |
return text | |
_from_string = jinja_env.from_string | |
def clean_for_braces(rtf_str, open_br, close_br, append=""): | |
first = True | |
template_text = "" | |
for start in rtf_str.split(open_br): | |
if first == True: | |
first = False | |
template_text += start | |
continue | |
# if start or close alone, jinja will raise so I don't. | |
if start.count(close_br) == 1: | |
to_clean, content = start.split(close_br) | |
to_clean = ("%r" % to_clean)[1:-1] # remove ' around str | |
to_clean = "".join(w.partition("}")[0].partition("\\")[0] | |
for w in to_clean.split(" ") | |
if not w.startswith("\\")) | |
to_clean = to_clean.replace(";", " ") | |
template_text += open_br + to_clean + append + close_br + content | |
return template_text | |
def template_from_rtf(rtf_str, *args, **kwargs): | |
rtf_str = clean_for_braces(rtf_str, *logic_braces) | |
rtf_str = clean_for_braces(rtf_str, *insert_braces) | |
template = jinja_env.from_string(rtf_str, *args, **kwargs) | |
return template | |
jinja_env.filters['date'] = render_date | |
jinja_env.filters['rtf'] = rtf_accents |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment