verdandi/mixins/templatemixin.py

55 lines
1.3 KiB
Python
Raw Normal View History

2015-02-26 20:26:39 +01:00
#!/usr/bin/env python2
import os
from dateutil import parser
2015-02-26 20:26:39 +01:00
class TemplateMixin(object):
template = "base.html"
url = "index.html"
context = {}
def get_context(self):
return self.context
def render(self, output_directory, jinja_env):
context = self.get_context()
self.render_files(context, output_directory, jinja_env)
2015-02-26 23:56:19 +01:00
def render_files(self, context, output_directory, jinja_env):
self.render_to_file(self.template, self.url, context, output_directory, jinja_env)
def render_to_file(self, template, url, context, output_directory, jinja_env):
template = jinja_env.get_template(template)
result = template.render(context)
out_path = os.path.join(output_directory, url)
2015-02-26 20:26:39 +01:00
out_dir = os.path.dirname(out_path)
if not os.path.isdir(out_dir):
os.mkdir(out_dir)
2015-02-26 23:56:19 +01:00
2016-01-28 23:14:46 +01:00
print "Rendering %s" % out_path
2015-02-26 20:26:39 +01:00
out_file = open(out_path, "wb")
2016-04-20 21:43:25 +02:00
out_file.write(result.encode('utf-8'))
2015-02-26 20:26:39 +01:00
out_file.close()
def read_content_file(self, path):
content_file = open(path, 'r')
result = {}
first_line = content_file.readline()
second_line = content_file.readline()
2016-04-20 21:43:25 +02:00
result['content'] = content_file.read().decode('utf-8')
result['creation_time'] = parser.parse(first_line)
result['edit_time'] = parser.parse(second_line)
content_file.close()
return result