def second_pass_render(request, content): """ Split on the secret delimiter and generate the token list by passing through text outside of phased blocks as single text tokens and tokenizing text inside the phased blocks. This ensures that nothing outside of the phased blocks is tokenized, thus eliminating the possibility of a template code injection vulnerability. """ result = tokens = [] for index, bit in enumerate(content.split(settings.SECRET_DELIMITER)): if index % 2: tokens = Lexer(bit, None).tokenize() else: tokens.append(Token(TOKEN_TEXT, bit)) # restore the previos context including the CSRF token context = RequestContext(request, restore_csrf_token(request, unpickle_context(bit))) # restore the loaded components (tags and filters) parser = Parser(tokens) unpickled_components = unpickle_components(bit) or [] for component in unpickled_components: lib = import_library(component) parser.add_library(lib) # render the piece with the restored context rendered = parser.parse().render(context) if settings.SECRET_DELIMITER in rendered: rendered = second_pass_render(request, rendered) result.append(rendered) return "".join(result)
def _get_templatelibs(self): """Return an iterable of template ``Library`` instances. Since we cannot support the {% load %} tag in Jinja, we have to register all libraries globally. """ from django.conf import settings from django.template import get_library, import_library libs = [] for app in settings.INSTALLED_APPS: ns = app + '.templatetags' try: path = __import__(ns, {}, {}, ['__file__']).__file__ path = os.path.dirname(path) # we now have the templatetags/ directory except ImportError: pass else: for filename in os.listdir(path): if filename == '__init__.py' or filename.startswith('.'): continue if filename.endswith('.py'): library_name = os.path.splitext(filename)[0] module = "%s.%s" % (ns, library_name) lib = import_library(module) if lib: libs.append(lib) # In addition to loading application libraries, support a custom list for libname in getattr(settings, 'JINJA2_DJANGO_TEMPLATETAG_LIBRARIES', ()): libs.append(get_library(libname)) return libs
def load_i18n_tag(parser, token): if token.contents.split()[1] == 'i18n': original_library = template.import_library('django.templatetags.i18n') library = template.Library() library.tags['trans'] = lineno_tag(original_library.tags['trans']) library.tags['blocktrans'] = lineno_tag( original_library.tags['blocktrans']) parser.add_library(library) return template.Node()
def get_library(library_name, app_name=None): """ (Forked from django.template.get_library) Load the template library module with the given name. If library is not already loaded loop over all templatetags modules to locate it. {% load somelib %} and {% load someotherlib %} loops twice. """ #TODO: add in caching. (removed when forked from django.template.get_library). templatetags_modules = get_templatetags_modules() tried_modules = [] best_match_lib = None last_found_lib = None app_name_parts = 0 if app_name: app_name_parts = app_name.count('.') for module in templatetags_modules: taglib_module = '%s.%s' % (module, library_name) tried_modules.append(taglib_module) lib = import_library(taglib_module) if not lib: continue last_found_lib = lib if not app_name: continue module_list = module.split('.') module_list.pop() # remove the last part 'templetags' current_app = '.'.join(module_list) if current_app == app_name: break start = len(module_list) - app_name_parts - 1 if start < 0: continue partial_app = '.'.join(module_list[start:]) if partial_app == app_name: best_match_lib = lib if best_match_lib: last_found_lib = best_match_lib if not last_found_lib: raise InvalidTemplateLibrary( "Template library %s not found, tried %s" % (library_name, ','.join(tried_modules))) return last_found_lib
def get_library(library_name, app_name=None): """ (Forked from django.template.get_library) Load the template library module with the given name. If library is not already loaded loop over all templatetags modules to locate it. {% load somelib %} and {% load someotherlib %} loops twice. """ # TODO: add in caching. (removed when forked from django.template.get_library). templatetags_modules = get_templatetags_modules() tried_modules = [] best_match_lib = None last_found_lib = None app_name_parts = 0 if app_name: app_name_parts = app_name.count(".") for module in templatetags_modules: taglib_module = "%s.%s" % (module, library_name) tried_modules.append(taglib_module) lib = import_library(taglib_module) if not lib: continue last_found_lib = lib if not app_name: continue module_list = module.split(".") module_list.pop() # remove the last part 'templetags' current_app = ".".join(module_list) if current_app == app_name: break start = len(module_list) - app_name_parts - 1 if start < 0: continue partial_app = ".".join(module_list[start:]) if partial_app == app_name: best_match_lib = lib if best_match_lib: last_found_lib = best_match_lib if not last_found_lib: raise InvalidTemplateLibrary( "Template library %s not found, tried %s" % (library_name, ",".join(tried_modules)) ) return last_found_lib
def _render_html(self, template_string, context={}): # :( if DJANGO_VERSION > (1,2): from django.template import import_library tag_lib = import_library('beproud.django.commons.tests.test_tags') else: from django.template import get_library tag_lib = get_library('beproud.django.commons.tests.test_tags') lexer = Lexer(template_string, self._make_origin()) parser = Parser(lexer.tokenize()) parser.add_library(tag_lib) nodelist = parser.parse() return nodelist.render(Context(context))
def add_to_builtins(module_name): """Add the given module to both Coffin's list of default template libraries as well as Django's. This makes sense, since Coffin libs are compatible with Django libraries. You can still use Django's own ``add_to_builtins`` to register directly with Django and bypass Coffin. TODO: Allow passing path to (or reference of) extensions and filters directly. This would make it easier to use this function with 3rd party Jinja extensions that do not know about Coffin and thus will not provide a Library object. XXX/TODO: Why do we need our own custom list of builtins? Our Library object is compatible, remember!? We can just add them directly to Django's own list of builtins. """ builtins.append(import_library(module_name)) django_add_to_builtins(module_name)
def load_django_filters(filters, library_names, use_default_filters): from django.template import get_library, import_library if use_default_filters: library = import_library('django.template.defaultfilters') if not library: raise InvalidTemplateLibrary( 'Couldn\'t load django.template.defaultfilters') # Update the dict for filters that don't already exist, i.e # jinja2's built-in filters. filters.update( dict((name, value) for (name, value) in library.filters.iteritems() if name not in filters)) for name in library_names: filters.update(get_library(name).filters)
def load_django_filters(filters, library_names, use_default_filters): if use_default_filters: library = import_library('django.template.defaultfilters') if not library: raise InvalidTemplateLibrary('Couldn\'t load django.template.defaultfilters') # Update the dict for filters that don't already exist, i.e # jinja2's built-in filters. filters.update(dict( (name, value) for (name, value) in library.filters.iteritems() if name not in filters )) for name in library_names: filters.update(get_library(name).filters)
def _get_templatelibs(self): """Return an iterable of template ``Library`` instances. Since we cannot support the {% load %} tag in Jinja, we have to register all libraries globally. """ from django.conf import settings from django.template import (get_library, import_library, InvalidTemplateLibrary) libs = [] for app in settings.INSTALLED_APPS: ns = app + '.templatetags' try: path = __import__(ns, {}, {}, ['__file__']).__file__ path = os.path.dirname( path) # we now have the templatetags/ directory except ImportError: pass else: for filename in os.listdir(path): if filename == '__init__.py' or filename.startswith('.'): continue if filename.endswith('.py'): try: module = "%s.%s" % (ns, os.path.splitext(filename)[0]) l = import_library(module) libs.append(l) except InvalidTemplateLibrary: pass # In addition to loading application libraries, support a custom list for libname in getattr(settings, 'JINJA2_DJANGO_TEMPLATETAG_LIBRARIES', ()): libs.append(get_library(libname)) return libs
def get_library(library_name, app_name=None): """ (Forked from django.template.get_library) Load the template library module with the given name. If library is not already loaded loop over all templatetags modules to locate it. {% load somelib %} and {% load someotherlib %} loops twice. """ #TODO: add in caching. (removed when forked from django.template.get_library). templatetags_modules = get_templatetags_modules() tried_modules = [] for module in templatetags_modules: taglib_module = '%s.%s' % (module, library_name) tried_modules.append(taglib_module) lib = import_library(taglib_module) if lib and app_name and taglib_module.split('.')[-3] == app_name: break if not lib: raise InvalidTemplateLibrary("Template library %s not found, tried %s" % (library_name, ','.join(tried_modules))) return lib
from board import forms as board_forms #from board.paginator import Paginator from board.decorators import parsingTag #from django.template import RequestContext #from django.core.urlresolvers import reverse #from django.template.loader import render_to_string from django.views.decorators.csrf import csrf_protect from django.utils import simplejson from django.contrib.contenttypes.models import ContentType from django.core.urlresolvers import reverse from django.contrib.humanize.templatetags import humanize from board.utils import EndlessPage import sys from django.utils.encoding import smart_str register = template.import_library("board.decorators") #@ parsingTag class TagsList(template.Node): def __init__(self, limit=15): self.limit = limit def render(self, context): from board.views.tag import list as tag_list return tag_list(context['request'], limit=self.limit, context_instance=context, discard_response=True)
from board import forms as board_forms #from board.paginator import Paginator from board.decorators import parsingTag #from django.template import RequestContext #from django.core.urlresolvers import reverse #from django.template.loader import render_to_string from django.views.decorators.csrf import csrf_protect from django.utils import simplejson from django.contrib.contenttypes.models import ContentType from django.core.urlresolvers import reverse from django.contrib.humanize.templatetags import humanize from board.utils import EndlessPage import sys from django.utils.encoding import smart_str register = template.import_library("board.decorators") #@ parsingTag class TagsList(template.Node): def __init__(self, limit = 15): self.limit = limit def render(self, context): from board.views.tag import list as tag_list return tag_list(context['request'], limit = self.limit, context_instance = context, discard_response = True) parsingTag(TagsList, "do_tags_list") class ProfilesNode(template.Node): def __init__(self, lst, varname = ''): self.lst = template.Variable(lst)
if m: for lib in m.groups()[0].rstrip().split(' '): try: l = get_library(lib) htmldjango_opts['filter'] += _get_opt_dict(l,'filters',lib) htmldjango_opts['tag'] += _get_opt_dict(l,'tags',lib) except Exception as e: if HTMLDJANGO_DEBUG: print("FAILED TO LOAD: %s" % lib) raise e # {{{2 load options # TODO At the moment this is being loaded every match htmldjango_opts = {} htmldjango_opts['load'] = get_tag_libraries() def_filters = import_library('django.template.defaultfilters') htmldjango_opts['filter'] = _get_opt_dict(def_filters,'filters','default') def_tags = import_library('django.template.defaulttags') htmldjango_opts['tag'] = _get_opt_dict(def_tags,'tags','default') load_app_tags() try: urls = __import__(mysettings.ROOT_URLCONF,fromlist=['foo']) except: urls = None def htmldjango_urls(pattern): matches = [] def get_urls(urllist,parent=None): for entry in urllist: if hasattr(entry,'name') and entry.name: