From 197f0a626dc333a4956a541ce556abb87bda8b46 Mon Sep 17 00:00:00 2001 From: Florian Dold Date: Tue, 14 Feb 2017 21:07:41 +0100 Subject: make template compilation a LOT faster By not doing template parsing and starting the python interpreter every time, templating only takes about a second on my machine now. --- template.py | 59 +++++++++++++++++++++++++++++++---------------------------- 1 file changed, 31 insertions(+), 28 deletions(-) (limited to 'template.py') diff --git a/template.py b/template.py index f872ad3e..179e32a7 100755 --- a/template.py +++ b/template.py @@ -8,45 +8,48 @@ # Note that the gettext files need to be prepared first. This script # is thus to be invoked via the Makefile. import os +import os.path import sys import re import gettext import jinja2 +import glob +import codecs -if len(sys.argv) < 3: - sys.exit("Usage: " + __file__ + " ") +env = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.dirname(__file__)), + extensions=["jinja2.ext.i18n"], + autoescape=False) -in_file = sys.argv[1] -locale = sys.argv[2] -name, ext = re.match(r"(.*)\.([^.]+)$", in_file.rstrip(".j2")).groups() +for in_file in glob.glob("*.j2"): + name, ext = re.match(r"(.*)\.([^.]+)$", in_file.rstrip(".j2")).groups() + tmpl = env.get_template(in_file) -tr = gettext.translation("messages", - localedir="locale", - languages=[locale]) + def self_localized(other_locale): + """ + Return URL for the current page in another locale. + """ + return "../" + other_locale + "/" + in_file.rstrip(".j2") -env = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.dirname(__file__)), - extensions=["jinja2.ext.i18n"], - autoescape=False) -env.install_gettext_translations(tr, newstyle=True) + def url_localized(filename): + return "../" + locale + "/" + filename -tmpl = env.get_template(in_file) + def url(x): + # TODO: look at the app root environment variable + # TODO: check if file exists + return "../" + x -def self_localized(other_locale): - """ - Return URL for the current page in another locale. - """ - return "../" + other_locale + "/" + in_file.rstrip(".j2") + for l in glob.glob("locale/*/"): + locale = os.path.basename(l[:-1]) -def url_localized(filename): - return "../" + locale + "/" + filename + tr = gettext.translation("messages", + localedir="locale", + languages=[locale]) -def url(x): - # TODO: look at the app root environment variable - # TODO: check if file exists - return "../" + x + env.install_gettext_translations(tr, newstyle=True) -import codecs -f = codecs.open("./" + locale + "/" + in_file.rstrip(".j2"), "w", "utf-8") -f.write(tmpl.render(lang=locale, url=url, self_localized=self_localized, url_localized=url_localized)) -f.close() + + content = tmpl.render(lang=locale, url=url, self_localized=self_localized, url_localized=url_localized) + out_name = "./" + locale + "/" + in_file.rstrip(".j2") + with codecs.open(out_name, "w", "utf-8") as f: + f.write(content) -- cgit v1.2.3