paramecio2fm/paramecio2/libraries/mtemplates.py

211 lines
7.3 KiB
Python

# Template frontend from mako.
from mako.template import Template
from flask import session, url_for
from mako.lookup import TemplateLookup
from os import path
from settings import config
import gettext
import sys
from paramecio2.libraries.i18n import I18n
from paramecio2.libraries.urls import make_url, make_media_url, add_get_parameters
from paramecio2.libraries.formsutils import csrf_token
def env_theme(module, cache_enabled=True, cache_impl='', cache_args={}, module_directory="./tmp/modules"):
"""Function for create an environment for mako templates
Function for create an environment for mako templates. Really is a shortcut for TemplateLookup mako function. You can define cache options and module_directory for templates compiled
Args:
module (str): The module where the templates can be founded
cache_enabled (boolean): If True then mako template cache is enabled, is False, mako template cache is disabled.
cache_args (dict): Cache Args dict parameter for TemplateLookup function from Mako templates. View Mako Templates documentation.
module_directory (str): Module directory parameter for TemplateLookup function from Mako templates. View Mako Templates documentation.
Returns:
TemplateLookup: Return TemplateLookup object
"""
ext=module[len(module)-3:]
if ext=='.py':
module=path.dirname(module)
standard_templates=path.dirname(__file__)+'/templates'
module_directory+='/'+module
module_templates=module+'/templates'
theme_templates='themes/'+config.theme+'/templates'
search_folders=[theme_templates, module_templates, standard_templates]
#if self.inject_folder is not None:
#search_folders.insert(1, self.inject_folder+'/templates')
#Standard templates
#print(standard_templates)
return TemplateLookup(directories=search_folders, default_filters=['h'], input_encoding='utf-8', encoding_errors='replace', cache_enabled=cache_enabled, cache_impl=cache_impl, cache_args=cache_args, module_directory=module_directory, filesystem_checks=config.reloader)
class PTemplate:
"""A class used how shortcuts for Mako template functions.
"""
templates_loaded={}
def __init__(self, environment):
"""A class used how shortcuts for Mako template functions.
This class is used to have a set of shortcuts and hooks to Mako templates functions and methods over a series of default options.
Args:
environment (TemplateLookup): A TemplateLookup object generated with env_theme function
Attributes:
autoescape_ext (set): A set of extensions file where automatic autoescape is used
environment (TemplateLookup): A TemplateLookup object generated with env_theme function
filters (list): A list of functions used for add filters to your templates.
js (list): A list of javascript sources for generate js html load tags.
"""
self.autoescape_ext=('html', 'htm', 'xml', 'phtml', 'js')
self.env=environment
self.filters={}
self.js={}
self.add_filter(I18n.lang)
#self.add_filter(make_url)
self.add_filter(make_media_url)
self.add_filter(url_for)
self.add_filter(csrf_token)
self.add_filter(add_get_parameters)
self.add_filter(self.add_js)
self.add_filter(self.load_js)
def add_js(self, js, module=''):
"""Function for add js to self.js attribute
Add a js file name to an attribute list called self.js with the <script> tag to add it to the header of an html code
Args:
js (str): The name of js file. Normally you save the file in media/js folder in module or theme
module (str): Optional. Where is saved the js file.
Returns:
None: Dummy return necessary because mako expect return something
"""
if not js in self.js:
self.js[js]='<script language="Javascript" src="{}"></script>'.format(make_media_url('js/'+js, module))
return ""
def load_js(self):
return "\n".join(self.js.values())
"""
def gettext(self, text):
return gettext.dgettext(self.domain_gettext, text)
"""
def load_template(self, template_file, **arguments):
"""Load a mako template and return the result
Load a mako template and return the results with different arguments applied
Args:
template_file (str): The name of template file. The template is searched using configuration defined in self.env
**arguments (mixed): Extra arguments with variables passed to template
Returns:
Return a template rendered using mako class from self.env
"""
"""
if self.prepare_gettext:
module_lang_dir=self.env.directories[1].replace('/templates', '/locales')
module_name=path.basename(module_lang_dir.replace('/locales', ''))
en = gettext.translation(module_name, localedir=module_lang_dir, languages=['en'])
en.install()
_=en.gettext
arguments.update({'_': _})
"""
template = self.env.get_template(template_file)
arguments.update(self.filters)
return template.render(**arguments)
def guess_autoescape(self, template_name):
"""Simple helper method for get an extension from filename
Args:
template_name (str): The template name
"""
if template_name is None or '.' not in template_name:
return False
ext = template_name.rsplit('.', 1)[1]
return ext in self.autoescape_ext
def render_template(self, template_file, **arguments):
"""Experimental method for parse a template
Experimental method for parse a template, similar to load_template but try cache the template loaded
Args:
js (str): The name of js file. Normally you save the file in media/js folder in module or theme
module (str): Optional. Where is saved the js file.
Returns:
None: Dummy return necessary because mako expect return something
"""
if not str(self.env.directories)+'/'+template_file in PTemplate.templates_loaded:
PTemplate.templates_loaded[str(self.env.directories)+'/'+template_file]=self.env.get_template(template_file)
arguments.update(self.filters)
return PTemplate.templates_loaded[str(self.env.directories)+'/'+template_file].render(**arguments)
def add_filter(self, filter_name):
"""Method for add filters to self.filters attributes
Method for add filters to self.filters attributes for use in templates
Args:
filter_name (function): Filter function
"""
self.filters[filter_name.__name__]=filter_name
def add_css_home_local(file_css, module):
pass
env=env_theme(__file__)
standard_t=PTemplate(env)