def __init__(self, position, user): self.position = position self.user = template.Variable(user) self.register = template.get_library("webapp.templatetags.webapp-tags") self.possible_tags = [] # we have to hit all apps' templatetags so our dashboard versions # get created. also gather all the possible tags for this position # # FIXME the first element is not shown the first time the dashboard # is displayed after runserver begins (because our fake tags haven't # been added to library yet. chicken or egg situation). A workaround # is putting a dummy element tag with a position that is never used # by a real templatetag for app in app_conf.values(): module = app["module"] + '.templatetags.' + app["type"] + '-tags' try: lib = template.get_library(module) #print lib.tags.keys() for key in lib.tags.keys(): if key.startswith(self.position): #print self.position + ' possibility: ' + key self.possible_tags.append(key) except Exception, e: # don't worry about apps that don't have templatetags continue
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 _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, InvalidTemplateLibrary libs = [] for a in settings.INSTALLED_APPS: try: path = __import__(a + '.templatetags', {}, {}, ['__file__']).__file__ path = os.path.dirname( path) # we now have the templatetags/ directory except ImportError: pass else: for f in os.listdir(path): if f == '__init__.py' or f.startswith('.'): continue if f.endswith('.py'): try: # TODO: will need updating when #6587 lands # libs.append(get_library( # "django.templatetags.%s" % os.path.splitext(f)[0])) l = get_library(os.path.splitext(f)[0]) libs.append(l) except InvalidTemplateLibrary: pass return libs
def friendly_load(parser, token): ''' Tries to load a custom template tag set. Non existing tag libraries are ignored. This means that, if used in conjuction with ``if_has_tag``, you can try to load the comments template tag library to enable comments even if the comments framework is not installed. For example:: {% load friendly_loader %} {% friendly_load comments webdesign %} {% if_has_tag render_comment_list %} {% render_comment_list for obj %} {% else %} {% if_has_tag lorem %} {% lorem %} {% endif_has_tag %} {% endif_has_tag %} ''' bits = token.contents.split() for taglib in bits[1:]: try: lib = get_library(taglib) parser.add_library(lib) except InvalidTemplateLibrary: pass return LoadNode()
def load(parser, token): """ Loads a custom template tag set. For example, to load the template tags in ``django/templatetags/news/photos.py``:: {% load news.photos %} Can also be used to load an individual tag/filter from a library:: {% load byline from news %} """ bits = token.contents.split() if len(bits) >= 4 and bits[-2] == "from": try: taglib = bits[-1] lib = get_library(taglib) except InvalidTemplateLibrary, e: raise TemplateSyntaxError("'%s' is not a valid tag library: %s" % (taglib, e)) else: temp_lib = Library() for name in bits[1:-2]: if name in lib.tags: temp_lib.tags[name] = lib.tags[name] # a name could be a tag *and* a filter, so check for both if name in lib.filters: temp_lib.filters[name] = lib.filters[name] elif name in lib.filters: temp_lib.filters[name] = lib.filters[name] else: raise TemplateSyntaxError("'%s' is not a valid tag or filter in tag library '%s'" % (name, taglib)) parser.add_library(temp_lib)
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, InvalidTemplateLibrary libs = [] for a in settings.INSTALLED_APPS: try: path = __import__(a + '.templatetags', {}, {}, ['__file__']).__file__ path = os.path.dirname(path) # we now have the templatetags/ directory except ImportError: pass else: for f in os.listdir(path): if f == '__init__.py': continue if f.endswith('.py'): try: # TODO: will need updating when #6587 lands # libs.append(get_library( # "django.templatetags.%s" % os.path.splitext(f)[0])) libs.append(get_library(os.path.splitext(f)[0])) except InvalidTemplateLibrary: pass return libs
def load_all_installed_template_libraries(): # Load/register all template tag libraries from installed apps. for module_name in template.get_templatetags_modules(): mod = import_module(module_name) try: libraries = [ os.path.splitext(p)[0] for p in os.listdir(os.path.dirname(upath(mod.__file__))) if p.endswith('.py') and p[0].isalpha() ] except OSError: libraries = [] for library_name in libraries: try: template.get_library(library_name) except template.InvalidTemplateLibrary: pass
def load_all_installed_template_libraries(): # Load/register all template tag libraries from installed apps. for e in templatetags.__path__: libraries = [os.path.splitext(p)[0] for p in os.listdir(e) if p.endswith('.py') and p[0].isalpha()] for library_name in libraries: try: lib = template.get_library("django.templatetags.%s" % library_name.split('.')[-1]) except template.InvalidTemplateLibrary: pass
def ajax_widget(request, library, name): from django.template import get_library lib = get_library(library) resp = lib.get_widget_view(name)(request) try: from djangologging import SUPPRESS_OUTPUT_ATTR setattr(resp, SUPPRESS_OUTPUT_ATTR, True) except ImportError: pass return resp
def load_all_installed_template_libraries(): # Load/register all template tag libraries from installed apps. for module_name in template.get_templatetags_modules(): mod = import_module(module_name) if not hasattr(mod, "__file__"): # e.g. packages installed as eggs continue try: libraries = [ os.path.splitext(p)[0] for p in os.listdir(os.path.dirname(upath(mod.__file__))) if p.endswith(".py") and p[0].isalpha() ] except OSError: continue else: for library_name in libraries: try: template.get_library(library_name) except template.InvalidTemplateLibrary: pass
def load_app_tags(): cb = vim.current.buffer for line in cb: m = re.compile('{% load (.*)%}').match(line) 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
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 load(parser, token): """ Load a custom template tag set. For example, to load the template tags in ``django/templatetags/news/photos.py``:: {% load news.photos %} """ bits = token.contents.split() for taglib in bits[1:]: # add the library to the parser try: lib = get_library("django.templatetags.%s" % taglib.split('.')[-1]) parser.add_library(lib) except InvalidTemplateLibrary, e: raise TemplateSyntaxError, "'%s' is not a valid tag library: %s" % (taglib, e)
def handle(self, *args, **options): if args: appname, = args style = color_style() if settings.ADMIN_FOR: settings_modules = [ __import__(m, {}, {}, ['']) for m in settings.ADMIN_FOR ] else: settings_modules = [settings] for settings_mod in settings_modules: for app in settings_mod.INSTALLED_APPS: try: templatetag_mod = __import__(app + '.templatetags', {}, {}, ['']) except ImportError: continue mod_path = inspect.getabsfile(templatetag_mod) mod_files = os.listdir(os.path.dirname(mod_path)) tag_files = [ i.rstrip('.py') for i in mod_files if i.endswith('.py') and i[0] != '_' ] app_labeled = False for taglib in tag_files: try: lib = get_library("django.templatetags.%s" % taglib) except: continue if not app_labeled: self.add_result('\nApp: %s' % style.MODULE_NAME(app)) app_labeled = True self.add_result('load: %s' % style.TAGLIB(taglib), 1) for items, label, style_func in [ (lib.tags, 'Tag:', style.TAG), (lib.filters, 'Filter:', style.FILTER) ]: for item in items: self.add_result( '%s %s' % (label, style_func(item)), 2) doc = inspect.getdoc(items[item]) if doc: self.add_result(format_block(doc, 12)) return self.results
def load(parser, token): """ Load a custom template tag set. For example, to load the template tags in ``django/templatetags/news/photos.py``:: {% load news.photos %} """ bits = token.contents.split() for taglib in bits[1:]: # add the library to the parser try: lib = get_library("django.templatetags.%s" % taglib.split('.')[-1]) parser.add_library(lib) except InvalidTemplateLibrary, e: raise TemplateSyntaxError, "'%s' is not a valid tag library: %s" % ( taglib, e)
def fake_templatetag(f): ''' Adds a fake (rendered -- not curried) templatetag to dashboard's templatetags and returns the original function unchanged so it can be registered normally as a proper templatetag in its home app. ''' from django import template register = template.get_library("webapp.templatetags.webapp-tags") # add the rendered template to dashboard templatetags library name = position if perm is not None: # add permission to the name so we'll have # 'position_name-app.perm_name' name = name + '-' + perm try: # add the rendered template to dashboard's library of tags register.tags.update({ name : massaman(f, path) }) except Exception,e: # if something goes wrong, pass the error along to the dashboard register.tags.update({ name : "Error loading %s. %s" % (f.func_name, e) })
def import_object(self): """ Import the taglibrary. Returns True if successful, False if an error occurred. """ # do an ordinary module import if not super(ModuleDocumenter, self).import_object(): return False try: # ask Django if specified module is a template tags library # and - if it is so - get and save Library instance #self.taglib = get_library(self.object.__name__) self.taglib = get_library(self.object.__name__.split('.', -1)) return True except InvalidTemplateLibrary, e: self.taglib = None self.directive.warn(unicode(e))
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(get_library(module_name)) django_add_to_builtins(module_name)
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 handle(self, *args, **options): if args: appname, = args style = color_style() if settings.ADMIN_FOR: settings_modules = [__import__(m, {}, {}, ['']) for m in settings.ADMIN_FOR] else: settings_modules = [settings] for settings_mod in settings_modules: for app in settings_mod.INSTALLED_APPS: try: templatetag_mod = __import__( app + '.templatetags', {}, {}, ['']) except ImportError: continue mod_path = inspect.getabsfile(templatetag_mod) mod_files = os.listdir(os.path.dirname(mod_path)) tag_files = [ i.rstrip('.py') for i in mod_files if i.endswith('.py') and i[0] != '_'] app_labeled = False for taglib in tag_files: try: lib = get_library(taglib) except: continue if not app_labeled: self.add_result('\nApp: %s' % style.MODULE_NAME(app)) app_labeled = True self.add_result('load: %s' % style.TAGLIB(taglib), 1) for items, label, style_func in [ (lib.tags, 'Tag:', style.TAG), (lib.filters, 'Filter:', style.FILTER)]: for item in items: self.add_result( '%s %s' % (label, style_func(item)), 2) doc = inspect.getdoc(items[item]) if doc: self.add_result(format_block(doc, 12)) return self.results
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 _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_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, InvalidTemplateLibrary libs = [] for a in settings.INSTALLED_APPS: try: path = __import__(a + '.templatetags', {}, {}, ['__file__']).__file__ path = os.path.dirname(path) # we now have the templatetags/ directory except ImportError: pass else: for f in os.listdir(path): if f == '__init__.py': continue if f.endswith('.py'): try: # TODO: will need updating when #6587 lands # libs.append(get_library( # "django.templatetags.%s" % os.path.splitext(f)[0])) l = get_library(os.path.splitext(f)[0]) if not isinstance(l, CoffinLibrary): # If this is only a standard Django library, # convert it. This will ensure that Django # filters in that library are converted and # made available in Jinja. l = CoffinLibrary.from_django(l) libs.append(l) except InvalidTemplateLibrary: pass return libs
def _getfilter(self, filtername): return template.get_library('setstatus_tags').filters[filtername]
def __init__(self,module): from django.template import get_library self._module = get_library(module)
def _reset_context(self): # monkeypatch a forced recalculation of the template context tags = get_library("markitup_tags") tags._markitup_context = _get_markitup_context()
def _get_all_extensions(self): from django.conf import settings from django.template import builtins as django_builtins from coffin.template import builtins as coffin_builtins from django.core.urlresolvers import get_callable # Note that for extensions, the order in which we load the libraries # is not maintained (https://github.com/mitsuhiko/jinja2/issues#issue/3). # Extensions support priorities, which should be used instead. extensions, filters, globals, tests, attrs = [], {}, {}, {}, {} def _load_lib(lib): if not isinstance(lib, CoffinLibrary): # If this is only a standard Django library, # convert it. This will ensure that Django # filters in that library are converted and # made available in Jinja. lib = CoffinLibrary.from_django(lib) extensions.extend(getattr(lib, 'jinja2_extensions', [])) filters.update(getattr(lib, 'jinja2_filters', {})) globals.update(getattr(lib, 'jinja2_globals', {})) tests.update(getattr(lib, 'jinja2_tests', {})) attrs.update(getattr(lib, 'jinja2_environment_attrs', {})) # Start with Django's builtins; this give's us all of Django's # filters courtasy of our interop layer. for lib in django_builtins: _load_lib(lib) # The stuff Jinja2 comes with by default should override Django. filters.update(jinja2_defaults.DEFAULT_FILTERS) tests.update(jinja2_defaults.DEFAULT_TESTS) globals.update(jinja2_defaults.DEFAULT_NAMESPACE) # Our own set of builtins are next, overwriting Jinja2's. for lib in coffin_builtins: _load_lib(lib) # Optionally, include the i18n extension. if settings.USE_I18N: extensions.append(_JINJA_I18N_EXTENSION_NAME) # Next, add the globally defined extensions extensions.extend(list(getattr(settings, 'JINJA2_EXTENSIONS', []))) def from_setting(setting, values_must_be_callable = False): retval = {} setting = getattr(settings, setting, {}) if isinstance(setting, dict): for key, value in setting.iteritems(): if values_must_be_callable and not callable(value): value = get_callable(value) retval[key] = value else: for value in setting: if values_must_be_callable and not callable(value): value = get_callable(value) retval[value.__name__] = value return retval tests.update(from_setting('JINJA2_TESTS', True)) filters.update(from_setting('JINJA2_FILTERS', True)) globals.update(from_setting('JINJA2_GLOBALS')) # Finally, add extensions defined in application's templatetag libraries libraries = self._get_templatelibs() # Load custom libraries. from django.template import get_library for libname in getattr(settings, 'JINJA2_DJANGO_TEMPLATETAG_LIBRARIES', ()): libraries.append(get_library(libname)) for lib in libraries: _load_lib(lib) attrs.update(getattr(lib, 'jinja2_environment_attrs', {})) return dict( extensions=extensions, filters=filters, globals=globals, tests=tests, attrs=attrs, )
def _get_all_extensions(self): from django.conf import settings from django.template import builtins as django_builtins from coffin.template import builtins as coffin_builtins from django.core.urlresolvers import get_callable # Note that for extensions, the order in which we load the libraries # is not maintained (https://github.com/mitsuhiko/jinja2/issues#issue/3). # Extensions support priorities, which should be used instead. extensions, filters, globals, tests, attrs = [], {}, {}, {}, {} def _load_lib(lib): if not isinstance(lib, CoffinLibrary): # If this is only a standard Django library, # convert it. This will ensure that Django # filters in that library are converted and # made available in Jinja. lib = CoffinLibrary.from_django(lib) extensions.extend(getattr(lib, 'jinja2_extensions', [])) filters.update(getattr(lib, 'jinja2_filters', {})) globals.update(getattr(lib, 'jinja2_globals', {})) tests.update(getattr(lib, 'jinja2_tests', {})) attrs.update(getattr(lib, 'jinja2_environment_attrs', {})) # Start with Django's builtins; this give's us all of Django's # filters courtasy of our interop layer. for lib in django_builtins: _load_lib(lib) # The stuff Jinja2 comes with by default should override Django. filters.update(jinja2_defaults.DEFAULT_FILTERS) tests.update(jinja2_defaults.DEFAULT_TESTS) globals.update(jinja2_defaults.DEFAULT_NAMESPACE) # Our own set of builtins are next, overwriting Jinja2's. for lib in coffin_builtins: _load_lib(lib) # Optionally, include the i18n extension. if settings.USE_I18N: extensions.append(_JINJA_I18N_EXTENSION_NAME) # Next, add the globally defined extensions extensions.extend(list(getattr(settings, 'JINJA2_EXTENSIONS', []))) def from_setting(setting, values_must_be_callable=False): retval = {} setting = getattr(settings, setting, {}) if isinstance(setting, dict): for key, value in setting.iteritems(): if values_must_be_callable and not callable(value): value = get_callable(value) retval[key] = value else: for value in setting: if values_must_be_callable and not callable(value): value = get_callable(value) retval[value.__name__] = value return retval tests.update(from_setting('JINJA2_TESTS', True)) filters.update(from_setting('JINJA2_FILTERS', True)) globals.update(from_setting('JINJA2_GLOBALS')) # Finally, add extensions defined in application's templatetag libraries libraries = self._get_templatelibs() # Load custom libraries. from django.template import get_library for libname in getattr(settings, 'JINJA2_DJANGO_TEMPLATETAG_LIBRARIES', ()): libraries.append(get_library(libname)) for lib in libraries: _load_lib(lib) attrs.update(getattr(lib, 'jinja2_environment_attrs', {})) return dict( extensions=extensions, filters=filters, globals=globals, tests=tests, attrs=attrs, )
def get_value(self, request): """Computes the real value of the variable, using the request.""" taglib, tagname = self.tagpath.rsplit('.', 1) return template.get_library(taglib).tags[tagname].get_value( request, *self.args, **self.kwargs)
for name in bits[1:-2]: if name in lib.tags: temp_lib.tags[name] = lib.tags[name] # a name could be a tag *and* a filter, so check for both if name in lib.filters: temp_lib.filters[name] = lib.filters[name] elif name in lib.filters: temp_lib.filters[name] = lib.filters[name] else: raise TemplateSyntaxError("'%s' is not a valid tag or filter in tag library '%s'" % (name, taglib)) parser.add_library(temp_lib) else: for taglib in bits[1:]: # add the library to the parser try: lib = get_library(taglib) parser.add_library(lib) except InvalidTemplateLibrary, e: raise TemplateSyntaxError("'%s' is not a valid tag library: %s" % (taglib, e)) return LoadNode() load = register.tag(load) # @register.tag def now(parser, token): """ Displays the date, formatted according to the given string. Uses the same format as PHP's ``date()`` function; see http://php.net/date for all the possible values.
def test_is_registered_as_a_templatetag_at_esi(self): library = template.get_library('esi') self.assert_('esi' in library.tags) self.assert_(library.tags['esi'] is esi)
from django.template import get_library from django.contrib.admin.templatetags.admin_list import result_headers from django.db import models from django.core.exceptions import ObjectDoesNotExist from django.utils.encoding import smart_unicode, force_unicode from django.utils.safestring import mark_safe from django.utils.html import escape, conditional_escape from django.contrib.admin.templatetags.admin_list import _boolean_icon from django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE from django.utils.translation import get_date_formats from django.utils.text import capfirst from django.utils import dateformat from book.models import Author REGISTER = get_library('django.templatetags.admin_list') def my_items_for_result(cl, result, form): ''' defines onclick function in book's change_list (returns _unicode_() instead of id ) ''' first = True cl_pk = cl.lookup_opts.pk.attname for field_name in cl.list_display: row_class = '' try: field = cl.lookup_opts.get_field(field_name) except models.FieldDoesNotExist: try:
def _reset_context(self): # monkeypatch a forced recalculation of the template context # format of get_library arg changed in 1.2 tags = get_library(markitup_tags) tags._markitup_context = _get_markitup_context()