| 969 | | def get_library(module_name): |
| 970 | | lib = libraries.get(module_name, None) |
| | 970 | def import_library(taglib_module): |
| | 971 | """Load a template tag library module. |
| | 972 | |
| | 973 | Verifies that the library contains a 'register' attribute, and |
| | 974 | returns that attribute as the representation of the library |
| | 975 | """ |
| | 976 | try: |
| | 977 | mod = import_module(taglib_module) |
| | 978 | except ImportError: |
| | 979 | return None |
| | 980 | try: |
| | 981 | return mod.register |
| | 982 | except AttributeError: |
| | 983 | raise InvalidTemplateLibrary("Template library %s does not have a variable named 'register'" % taglib_module) |
| | 984 | |
| | 985 | templatetags_modules= [] |
| | 986 | |
| | 987 | def get_templatetags_modules(): |
| | 988 | """Return the list of all available template tag modules. |
| | 989 | |
| | 990 | Caches the result for faster access. |
| | 991 | """ |
| | 992 | if not templatetags_modules: |
| | 993 | # Populate list once per thread. |
| | 994 | for app_module in ['django'] + list(settings.INSTALLED_APPS): |
| | 995 | try: |
| | 996 | templatetag_module = '%s.templatetags' % app_module |
| | 997 | import_module(templatetag_module) |
| | 998 | templatetags_modules.append(templatetag_module) |
| | 999 | except ImportError: |
| | 1000 | continue |
| | 1001 | return templatetags_modules |
| | 1002 | |
| | 1003 | def get_library(library_name): |
| | 1004 | """ |
| | 1005 | Load the template library module with the given name. |
| | 1006 | |
| | 1007 | If library is not already loaded loop over all templatetags modules to locate it. |
| | 1008 | |
| | 1009 | {% load somelib %} and {% load someotherlib %} loops twice. |
| | 1010 | |
| | 1011 | Subsequent loads eg. {% load somelib %} in the same thread will grab the cached |
| | 1012 | module from libraries. |
| | 1013 | """ |
| | 1014 | lib = libraries.get(library_name, None) |
| 972 | | try: |
| 973 | | mod = import_module(module_name) |
| 974 | | except ImportError, e: |
| 975 | | raise InvalidTemplateLibrary("Could not load template library from %s, %s" % (module_name, e)) |
| 976 | | try: |
| 977 | | lib = mod.register |
| 978 | | libraries[module_name] = lib |
| 979 | | except AttributeError: |
| 980 | | raise InvalidTemplateLibrary("Template library %s does not have a variable named 'register'" % module_name) |
| | 1016 | templatetags_modules = get_templatetags_modules() |
| | 1017 | tried_modules = [] |
| | 1018 | for module in templatetags_modules: |
| | 1019 | taglib_module = str('%s.%s' % (module, library_name)) |
| | 1020 | tried_modules.append(taglib_module) |
| | 1021 | lib = import_library(taglib_module) |
| | 1022 | if lib: |
| | 1023 | libraries[library_name] = lib |
| | 1024 | break |
| | 1025 | if not lib: |
| | 1026 | raise InvalidTemplateLibrary("Template library %s not found, tried %s" % (library_name, ','.join(tried_modules))) |