Exemple #1
0
def tryload(parser, token):
	bits = token.contents.split()
	if len(bits) >= 4 and bits[-2] == "from":
		try:
			taglib = bits[-1]
			lib = get_library(taglib)
		except InvalidTemplateLibrary as e:
			return LoadNode()
		else:
			temp_lib = Library()
			for name in bits[1:-2]:
				if name in lib.tags:
					temp_lib.tags[name] = lib.tags[name]
					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:
					return LoadNode()
			parser.add_library(temp_lib)
	else:
		for taglib in bits[1:]:
			try:
				lib = get_library(taglib)
				parser.add_library(lib)
			except InvalidTemplateLibrary as e:
				return LoadNode()
	
	return LoadNode()
Exemple #2
0
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 %}

    """
    # token.split_contents() isn't useful here because this tag doesn't accept variable as arguments
    bits = token.contents.split()
    if len(bits) >= 4 and bits[-2] == "from":
        try:
            taglib = bits[-1]
            lib = get_library(taglib)
        except InvalidTemplateLibrary as 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)
    else:
        for taglib in bits[1:]:
            # add the library to the parser
            try:
                lib = get_library(taglib)
                parser.add_library(lib)
            except InvalidTemplateLibrary as e:
                raise TemplateSyntaxError("'%s' is not a valid tag library: %s" %
                                          (taglib, e))
    return LoadNode()
Exemple #3
0
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()
Exemple #4
0
def get_django_filter(django_filter, load='django'):

    if django.VERSION < (1, 9):
        from django.template.base import get_library
        if load and not load == 'django':
            library = get_library(load)
        else:
            library_path = 'django.template.defaultfilters'
            if django.VERSION > (1, 8):
                from django.template.base import import_library
                library = import_library(library_path)
            else:
                from django.template import import_library
                library = import_library(library_path)

    else:
        from django.template.backends.django import get_installed_libraries
        from django.template.library import import_library
        libraries = get_installed_libraries()
        if load and not load == 'django':
            library_path = libraries.get(load)
            if not library_path:
                raise Exception('templatetag "{}" is not registered'.format(load))
        else:
            library_path = 'django.template.defaultfilters'

        library = import_library(library_path)
    filter_method = library.filters.get(django_filter)
    if not filter_method:
        raise Exception('filter "{}" not exist on {} templatetag package'.format(
            django_filter, load
        ))

    return filter_method
Exemple #5
0
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)
Exemple #6
0
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 as 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)
    else:
        for taglib in bits[1:]:
            # add the library to the parser
            try:
                lib = get_library(taglib)
                parser.add_library(lib)
            except InvalidTemplateLibrary as e:
                raise TemplateSyntaxError("'%s' is not a valid tag library: %s" %
                                          (taglib, e))
    return LoadNode()
 def load_library_for(self, block):
     try:
         lib = get_library(block.library)
         self.parser.add_library(lib)
     except InvalidTemplateLibrary as e:
         raise template.TemplateSyntaxError(
             "'%s' is not a valid tag library: %s" % (block.library, e)
         )
Exemple #8
0
    def render(self, context):
        name = (
            self.name.resolve(context) if hasattr(self.name, 'resolve')
            else self.name
        )

        # really quite hacky, but it works
        lib = get_library(name)
        module = lib.tags[name].__self__
        return module().render(context)
Exemple #9
0
def load_all_installed_template_libraries():
    # Load/register all template tag libraries from installed apps.
    for module_name in 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:
                    get_library(library_name)
                except InvalidTemplateLibrary:
                    pass
Exemple #10
0
def load_all_installed_template_libraries():
    # Load/register all template tag libraries from installed apps.
    for module_name in 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:
                    get_library(library_name)
                except InvalidTemplateLibrary:
                    pass
Exemple #11
0
    def handle(self, *args, **options):
        if args:
            appname, = args

        style = color_style()

        if getattr(settings, 'ADMIN_FOR', None):
            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('App: %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
Exemple #12
0
def load_tag_library(libname):
    """Load a templatetag library on multiple Django versions.

    Returns None if the library isn't loaded.
    """
    if django.VERSION < (1, 9):
        from django.template.base import get_library, InvalidTemplateLibrary
        try:
            lib = get_library(libname)
            return lib
        except InvalidTemplateLibrary:
            return None
    else:
        from django.template.backends.django import get_installed_libraries
        from django.template.library import InvalidTemplateLibrary
        try:
            lib = get_installed_libraries()[libname]
            lib = importlib.import_module(lib).register
            return lib
        except (InvalidTemplateLibrary, KeyError):
            return None
Exemple #13
0
def get_templatetag_members(template_name, loaded_modules, output=sys.stdout):
    """
    Get the names of tags and filters from available templatetags modules.

    :returns: {'somelib': [tags]}, {'somelib': [filters]}
    """
    tags = {}
    filters = {}
    for module in loaded_modules:
        try:
            lib = get_library(module)
        except InvalidTemplateLibrary:
            msg = ('Unable to locate the loaded library! Library: {}; '
                   'Template: {}\n').format(module, template_name)
            output.write(msg)
            tags[module] = []
            continue
        tags[module] = lib.tags.keys()
        filters[module] = lib.filters.keys()

    return tags, filters
    def handle(self, *args, **options):
        if args:
            appname, = args

        style = color_style()

        if getattr(settings, 'ADMIN_FOR', None):
            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('App: %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
Exemple #15
0
def get_templatetag_library(module):
    """Get the templatetag module's Library instance.

    Needed for extracting template tags and filters.

    Args:
        module {str}: module's name (e.g. 'app_tags')

    Returns:
        {Library}

    Raises:
        {AttributeError}: nonexistent module
        {InvalidTemplateLibrary}: the module does not have a variable
            named `register`

    """
    try:
        if import_library is not None and get_installed_libraries is not None:
            return import_library(get_installed_libraries().get(module))
        else:
            return get_library(module)
    except (AttributeError, InvalidTemplateLibrary):
        raise
Exemple #16
0
                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()

@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.

    Sample usage::
Exemple #17
0
                    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.
Exemple #18
0
def load_library(name):
    return SynthLibrary(base.get_library(name))