def handle(self, *args, **options): # Due to the use of LaxOptionParser ``args`` now contains all # unparsed options, and ``options`` those that the Django command # has declared. DjangoConfigStorage.force_debug = True # Create log log = logging.getLogger('django-assets') log.setLevel({0: logging.WARNING, 1: logging.INFO, 2: logging.DEBUG}[int(options.get('verbosity', 1))]) log.addHandler(logging.StreamHandler()) # If the user requested it, search for bundles defined in templates if options.get('parse_templates'): log.info('Searching templates...') # Note that we exclude container bundles. By their very nature, # they are guaranteed to have been created by solely referencing # other bundles which are already registered. get_env().add(*[b for b in self.load_from_templates() if not b.is_container]) if len(get_env()) == 0: DjangoConfigStorage.force_debug = False raise CommandError('No asset bundles were found. ' 'If you are defining assets directly within your ' 'templates, you want to use the --parse-templates ' 'option.') prog = "%s assets" % path.basename(sys.argv[0]) impl = GenericArgparseImplementation( env=get_env(), log=log, no_global_options=True, prog=prog) try: impl.run_with_argv(args) except AssetCommandError, e: raise CommandError(e)
def handle(self, *args, **options): # Due to the use of LaxOptionParser ``args`` now contains all # unparsed options, and ``options`` those that the Django command # has declared. # Create log log = logging.getLogger('django-assets') log.setLevel({0: logging.WARNING, 1: logging.INFO, 2: logging.DEBUG}[int(options.get('verbosity', 1))]) log.addHandler(logging.StreamHandler()) # If the user requested it, search for bundles defined in templates if options.get('parse_templates'): log.info('Searching templates...') # Note that we exclude container bundles. By their very nature, # they are guaranteed to have been created by solely referencing # other bundles which are already registered. get_env().add(*[b for b in self.load_from_templates() if not b.is_container]) if len(get_env()) == 0: raise CommandError('No asset bundles were found. ' 'If you are defining assets directly within your ' 'templates, you want to use the --parse-templates ' 'option.') prog = "%s assets" % path.basename(sys.argv[0]) impl = GenericArgparseImplementation( env=get_env(), log=log, no_global_options=True, prog=prog) try: impl.run_with_argv(args) except AssetCommandError, e: raise CommandError(e)
def handle(self, *args, **options): valid_commands = CommandLineEnvironment.Commands if len(args) > 1: raise CommandError('Invalid number of subcommands passed: %s' % ", ".join(args)) elif len(args) == 0: raise CommandError('You need to specify a subcommand: %s' % ', '.join(valid_commands)) # Create log log = logging.getLogger('django-assets') log.setLevel({0: logging.WARNING, 1: logging.INFO, 2: logging.DEBUG}[int(options.get('verbosity', 1))]) log.addHandler(logging.StreamHandler()) # If the user requested it, search for bundles defined in templates if options.get('parse_templates'): log.info('Searching templates...') # Note that we exclude container bundles. By their very nature, # they are guaranteed to have been created by solely referencing # other bundles which are already registered. get_env().add(*[b for b in self.load_from_templates() if not b.is_container]) if len(get_env()) == 0: raise CommandError('No asset bundles were found. ' 'If you are defining assets directly within your ' 'templates, you want to use the --parse-templates ' 'option.') # Execute the requested subcommand cmd = CommandLineEnvironment(get_env(), log) try: cmd.invoke(args[0]) except AssetCommandError, e: raise CommandError(e)
def test_default_options(self): """The builtin options have different names within the Django settings, to make it obvious they belong to django-assets. """ settings.ASSETS_EXPIRE = 'timestamp' assert get_env().config['expire'] == settings.ASSETS_EXPIRE settings.MEDIA_ROOT = 'FOO' assert get_env().directory == 'FOO' get_env().directory = 'BAR' assert settings.MEDIA_ROOT == 'BAR'
def resolve_bundle(name): # If a bundle with that name exists, use it. Otherwise, # assume a filename is meant. try: return get_env()[name] except KeyError: return name
def load_from_templates(self): # Using the Django loader bundles = DjangoLoader().load_bundles() # Using the Jinja loader, if available try: import jinja2 except ImportError: pass else: from webassets.ext.jinja2 import Jinja2Loader, AssetsExtension jinja2_envs = [] # Prepare a Jinja2 environment we can later use for parsing. # If not specified by the user, put in there at least our own # extension, which we will need most definitely to achieve anything. _jinja2_extensions = getattr(settings, 'ASSETS_JINJA2_EXTENSIONS', False) if not _jinja2_extensions: _jinja2_extensions = [AssetsExtension.identifier] jinja2_envs.append(jinja2.Environment(extensions=_jinja2_extensions)) try: from coffin.common import get_env as get_coffin_env except ImportError: pass else: jinja2_envs.append(get_coffin_env()) bundles.extend(Jinja2Loader(get_env(), get_django_template_dirs(), jinja2_envs).load_bundles()) return bundles
def list(self, ignore_patterns): # While ``StaticFileStorage`` itself is smart enough not to stumble # over this finder returning the full contents of STATIC_ROOT via # ``AssetsFileStorage``, ``CachedAssetsFileStorage`` is not. It would # create hashed versions of already hashed files. # # Since the development ``serve`` view will not use this ``list()`` # method, but the ``collectstatic`` command does, we can customize # it to deal with ``CachedAssetsFileStorage``. # # We restrict the files returned to known bundle output files. Those # will then be post-processed by ``CachedAssetsFileStorage`` and # properly hashed and rewritten. # # See also this discussion: # https://github.com/miracle2k/webassets/issues/114 env = get_env() if env.directory == getattr(settings, 'STATIC_ROOT'): for bundle in env: try: output = bundle.resolve_output(env) except BundleError: # We don't have a version for this bundle continue if not matches_patterns(output, ignore_patterns) and \ self.storage.exists(output): yield output, self.storage else: # When ASSETS_ROOT is a separate directory independent of # STATIC_ROOT, we're good just letting all files be collected. for output in super(AssetsFinder, self).list(ignore_patterns): yield output
def load_from_templates(self): # Using the Django loader bundles = DjangoLoader().load_bundles() # Using the Jinja loader, if available try: import jinja2 except ImportError: pass else: from webassets.ext.jinja2 import Jinja2Loader, AssetsExtension jinja2_envs = [] # Prepare a Jinja2 environment we can later use for parsing. # If not specified by the user, put in there at least our own # extension, which we will need most definitely to achieve anything. _jinja2_extensions = getattr(settings, 'ASSETS_JINJA2_EXTENSIONS', False) if not _jinja2_extensions: _jinja2_extensions = [AssetsExtension.identifier] jinja2_envs.append( jinja2.Environment(extensions=_jinja2_extensions)) try: from coffin.common import get_env as get_coffin_env except ImportError: pass else: jinja2_envs.append(get_coffin_env()) bundles.extend( Jinja2Loader(get_env(), get_django_template_dirs(), jinja2_envs).load_bundles()) return bundles
def list(self, ignore_patterns): # While ``StaticFileStorage`` itself is smart enough not to stumble # over this finder returning the full contents of STATIC_ROOT via # ``AssetsFileStorage``, ``CachedAssetsFileStorage`` is not. It would # create hashed versions of already hashed files. # # Since the development ``serve`` view will not use this ``list()`` # method, but the ``collectstatic`` command does, we can customize # it to deal with ``CachedAssetsFileStorage``. # # We restrict the files returned to known bundle output files. Those # will then be post-processed by ``CachedAssetsFileStorage`` and # properly hashed and rewritten. # # See also this discussion: # https://github.com/miracle2k/webassets/issues/114 env = get_env() if env.directory == getattr(settings, "STATIC_ROOT"): for bundle in env: try: output = bundle.resolve_output(env) except BundleError: # We don't have a version for this bundle continue if not matches_patterns(output, ignore_patterns) and self.storage.exists(output): yield output, self.storage else: # When ASSETS_ROOT is a separate directory independent of # STATIC_ROOT, we're good just letting all files be collected. for output in super(AssetsFinder, self).list(ignore_patterns): yield output
def get_assets(*bundle_names): env = get_env() assets = [] for name in bundle_names: if name in env: urls = [url.replace(env.url, '', 1) for url in env[name].urls()] assets.extend(urls) return assets
def test_default_options(self): """The builtin options have different names within the Django settings, to make it obvious they belong to django-assets. """ settings.ASSETS_URL_EXPIRE = True assert get_env().config['url_expire'] == settings.ASSETS_URL_EXPIRE settings.ASSETS_ROOT = 'FOO_ASSETS' settings.STATIC_ROOT = 'FOO_STATIC' settings.MEDIA_ROOT = 'FOO_MEDIA' # Pointing to ASSETS_ROOT assert get_env().directory.endswith('FOO_ASSETS') get_env().directory = 'BAR' assert settings.ASSETS_ROOT == 'BAR' # Pointing to STATIC_ROOT delsetting('ASSETS_ROOT') assert get_env().directory.endswith('FOO_STATIC') get_env().directory = 'BAR' assert settings.STATIC_ROOT == 'BAR' # Pointing to MEDIA_ROOT; Note we only # set STATIC_ROOT to None rather than deleting # it, a scenario that may occur in the wild. settings.STATIC_ROOT = None assert get_env().directory.endswith('FOO_MEDIA') get_env().directory = 'BAR' assert settings.MEDIA_ROOT == 'BAR'
def handle(self, *args, **options): # Due to the use of LaxOptionParser ``args`` now contains all # unparsed options, and ``options`` those that the Django command # has declared. # Create log log = logging.getLogger('django-assets') log.setLevel({ 0: logging.WARNING, 1: logging.INFO, 2: logging.DEBUG }[int(options.get('verbosity', 1))]) log.addHandler(logging.StreamHandler()) # If the user requested it, search for bundles defined in templates if options.get('parse_templates'): log.info('Searching templates...') # Note that we exclude container bundles. By their very nature, # they are guaranteed to have been created by solely referencing # other bundles which are already registered. get_env().add( *[b for b in self.load_from_templates() if not b.is_container]) if len(get_env()) == 0: log.info("No asset bundles were found. " "If you are defining assets directly within your " "templates, you want to use the --parse-templates " "option.") return prog = "%s assets" % path.basename(sys.argv[0]) impl = GenericArgparseImplementation(env=get_env(), log=log, no_global_options=True, prog=prog) try: # The webassets script runner may either return None on success (so # map that to zero) or a return code on build failure (so raise # a Django CommandError exception when that happens) retval = impl.run_with_argv(args) or 0 if retval != 0: raise CommandError('The webassets build script exited with ' 'a non-zero exit code (%d).' % retval) except AssetCommandError as e: raise CommandError(e)
def test_default_options(self): """The builtin options have different names within the Django settings, to make it obvious they belong to django-assets. """ settings.ASSETS_URL_EXPIRE = True assert get_env().config["url_expire"] == settings.ASSETS_URL_EXPIRE settings.ASSETS_ROOT = "FOO_ASSETS" settings.STATIC_ROOT = "FOO_STATIC" settings.MEDIA_ROOT = "FOO_MEDIA" # Pointing to ASSETS_ROOT assert get_env().directory == "FOO_ASSETS" get_env().directory = "BAR" assert settings.ASSETS_ROOT == "BAR" # Pointing to STATIC_ROOT delsetting("ASSETS_ROOT") assert get_env().directory == "FOO_STATIC" get_env().directory = "BAR" assert settings.STATIC_ROOT == "BAR" # Pointing to MEDIA_ROOT; Note we only # set STATIC_ROOT to None rather than deleting # it, a scenario that may occur in the wild. settings.STATIC_ROOT = None assert get_env().directory == "FOO_MEDIA" get_env().directory = "BAR" assert settings.MEDIA_ROOT == "BAR"
def handle(self, *args, **options): # For django to work, we need to populate apps and models as soon as possible # If the apps have not yet been populated by now (as is the case when using uwsgi), # populate. from django.db.models.loading import cache cache._populate() # Due to the use of LaxOptionParser ``args`` now contains all # unparsed options, and ``options`` those that the Django command # has declared. # Create log log = logging.getLogger('django-assets') log.setLevel({0: logging.WARNING, 1: logging.INFO, 2: logging.DEBUG}[int(options.get('verbosity', 1))]) log.addHandler(logging.StreamHandler()) # If the user requested it, search for bundles defined in templates if options.get('parse_templates'): log.info('Searching templates...') # Note that we exclude container bundles. By their very nature, # they are guaranteed to have been created by solely referencing # other bundles which are already registered. get_env().add(*[b for b in self.load_from_templates() if not b.is_container]) if len(get_env()) == 0: raise CommandError('No asset bundles were found. ' 'If you are defining assets directly within your ' 'templates, you want to use the --parse-templates ' 'option.') prog = "%s assets" % path.basename(sys.argv[0]) impl = GenericArgparseImplementation( env=get_env(), log=log, no_global_options=True, prog=prog) try: # The webassets script runner may either return None on success (so # map that to zero) or a return code on build failure (so raise # a Django CommandError exception when that happens) retval = impl.run_with_argv(args) or 0 if retval != 0: raise CommandError('The webassets build script exited with ' 'a non-zero exit code (%d).' % retval) except AssetCommandError as e: raise CommandError(e)
def test_deprecated_options(self): try: django_env_reset() with check_warnings(("", ImminentDeprecationWarning)) as w: settings.ASSETS_EXPIRE = 'filename' assert_raises(DeprecationWarning, get_env) django_env_reset() with check_warnings(("", ImminentDeprecationWarning)) as w: settings.ASSETS_EXPIRE = 'querystring' assert get_env().url_expire == True with check_warnings(("", ImminentDeprecationWarning)) as w: django_env_reset() settings.ASSETS_UPDATER = 'never' assert get_env().auto_build == False finally: delsetting('ASSETS_EXPIRE') delsetting('ASSETS_UPDATER')
def url(src, *args, **kwargs): src = src.format(*args, **kwargs).replace('//', '/') try: ret = url._cache[src] except KeyError: bundle = Bundle(src, output=src, merge=False) urls = bundle.urls(env=get_env(), binary=True) ret = urls[0] url._cache[src] = ret return ret
def render(self, context): bundle = self.resolve(context) result = u"" for url in bundle.urls(env=get_env()): context.update({'ASSET_URL': url}) try: result += self.childnodes.render(context) finally: context.pop() return result
def build_assets(): """Build assets like ./manage.py assets build does""" if settings.ASSETS_AUTO_BUILD: return env = assets_env.get_env() argparser = GenericArgparseImplementation(env=env, no_global_options=False) errored = argparser.run_with_argv(["build"]) or 0 if errored != 0: raise Exception("Asset building failed with error code %d" % errored)
def render(self, context): bundle = self.resolve(context) result = u"" with bundle.bind(get_env()): for url in bundle.urls(): context.update({'ASSET_URL': url, 'EXTRA': bundle.extra}) try: result += self.childnodes.render(context) finally: context.pop() return result
def build_assets(): """Call django_assets ./manage.py assets build if the app is present.""" cwd = os.getcwd() try: from webassets.script import GenericArgparseImplementation from django_assets.env import get_env prog = "%s assets" % os.path.basename(sys.argv[0]) impl = GenericArgparseImplementation( env=get_env(), log=LOGGER, no_global_options=True, prog=prog) impl.run_with_argv(["build"]) except ImportError: pass os.chdir(cwd)
def build_assets(): """Call django_assets ./manage.py assets build if the app is present.""" cwd = os.getcwd() try: from webassets.script import GenericArgparseImplementation from django_assets.env import get_env prog = "%s assets" % os.path.basename(sys.argv[0]) impl = GenericArgparseImplementation(env=get_env(), log=LOGGER, no_global_options=True, prog=prog) impl.run_with_argv(["build"]) except ImportError: pass os.chdir(cwd)
def environment(**options): env = Environment(**options) env.globals.update({ 'static': staticfiles_storage.url, 'url': url, 'assets': assets, # 'gravatar_url': get_avatar_url, 'get_current_language': get_language, 'get_available_languages': get_available_languages, 'get_language_info_list': get_language_info_list, # 'switch': gargoyle.is_active, # 'avatar_url': avatar_url }) env.filters.update( datetimeformat=babel.datetimefmt, dateformat=babel.datefmt, timeformat=babel.timefmt, natural_period=natural_period, # timedeltaformat=format_timedelta, numberformat=babel.numberfmt, decimalformat=babel.decimalfmt, currencyformat=babel.currencyfmt, percentformat=babel.percentfmt, scientificformat=babel.scientificfmt, append_get=do_append_get, class_name=do_class_name, ) env.add_extension('jinja2.ext.loopcontrols') env.add_extension('jinja2.ext.with_') env.add_extension('dinja2.ext.active') # from ext.relative_templates import RelativeInclude # env.add_extension(RelativeInclude) # env.add_extension('jinja2_highlight.HighlightExtension') # env.add_extension('jinja2htmlcompress.HTMLCompress') env.add_extension('webassets.ext.jinja2.AssetsExtension') env.assets_environment = get_env() env.add_extension('jinja2.ext.i18n') if settings.USE_I18N: from django.utils import translation env.install_gettext_translations(translation, newstyle=True) else: # pragma: no cover env.install_null_translations(newstyle=True) return env
def setup(self): TempDirHelper.setup(self) # Reset the webassets environment. django_env_reset() self.m = get_env() # Use a temporary directory as MEDIA_ROOT settings.MEDIA_ROOT = self.create_directories('media')[0] # Some other settings without which we are likely to run # into errors being raised as part of validation. setattr(settings, 'DATABASES', {}) settings.DATABASES['default'] = {'ENGINE': ''} # Unless we explicitly test it, we don't want to use # the cache during testing. self.m.cache = False
def setup(self): TempDirHelper.setup(self) # Reset the webassets environment. django_env_reset() self.env = get_env() # Use a temporary directory as MEDIA_ROOT settings.MEDIA_ROOT = self.create_directories("media")[0] # Some other settings without which we are likely to run # into errors being raised as part of validation. setattr(settings, "DATABASES", {}) settings.DATABASES["default"] = {"ENGINE": ""} # Unless we explicitly test it, we don't want to use the cache during # testing. self.env.cache = False self.env.manifest = False
def test_default_options(self): """The builtin options have different names within the Django settings, to make it obvious they belong to django-assets. """ settings.ASSETS_EXPIRE = 'timestamp' assert get_env().config['expire'] == settings.ASSETS_EXPIRE settings.ASSETS_ROOT = 'FOO_ASSETS' settings.STATIC_ROOT = 'FOO_STATIC' settings.MEDIA_ROOT = 'FOO_MEDIA' # Pointing to ASSETS_ROOT assert get_env().directory == 'FOO_ASSETS' get_env().directory = 'BAR' assert settings.ASSETS_ROOT == 'BAR' # Pointing to STATIC_ROOT delattr(settings, 'ASSETS_ROOT') assert get_env().directory == 'FOO_STATIC' get_env().directory = 'BAR' assert settings.STATIC_ROOT == 'BAR' # Pointing to MEDIA_ROOT delattr(settings, 'STATIC_ROOT') assert get_env().directory == 'FOO_MEDIA' get_env().directory = 'BAR' assert settings.MEDIA_ROOT == 'BAR'
# -*- coding: utf-8 -*- # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at http://mozilla.org/MPL/2.0/. # # Copyright 2012 Helsinki City Library from django.conf import settings from django_assets.env import get_env settings.TEMPLATE_ENV.assets_environment = get_env()
filters = value warnings.warn('The "filter" option of the {% assets %} ' 'template tag has been renamed to ' '"filters" for consistency reasons.', ImminentDeprecationWarning) # positional arguments are source files elif name is None: files.append(value) else: raise template.TemplateSyntaxError('Unsupported keyword argument "%s"'%name) # capture until closing tag childnodes = parser.parse(("endassets",)) parser.delete_first_token() return AssetsNode(filters, output, files, childnodes) # If Coffin is installed, expose the Jinja2 extension try: from coffin.template import Library as CoffinLibrary except ImportError: register = template.Library() else: register = CoffinLibrary() from webassets.ext.jinja2 import AssetsExtension from django_assets.env import get_env register.tag(AssetsExtension, environment={'assets_environment': get_env()}) # expose the default Django tag register.tag('assets', assets)
def __init__(self, location=None, base_url=None, *args, **kwargs): super(AssetsFileStorage, self).__init__(location or get_env().directory, base_url or get_env().url, *args, **kwargs)
def test_custom_options(self): settings.FOO = 42 assert get_env().config['foo'] == 42 # Also, we are caseless. assert get_env().config['foO'] == 42
def __init__(self, *a, **kw): Jinja2Environment.__init__(self, *a, **kw) from django_assets.env import get_env self.assets_environment = get_env()
def __init__(self, *a, **kw): Bundle.__init__(self, *a, **kw) self.env = get_env() # Kind of hacky, but gives us access to the last Bundle # instance used by our Django template tag. test_instance.the_bundle = self
from django_assets import Bundle, register from django_assets.env import get_env get_env().append_path("app/static") base_js = Bundle('bower_components/jquery/dist/jquery.js', 'bower_components/jquery.cookie/jquery.cookie.js', 'bower_components/google-code-prettify/bin/prettify.min.js', 'lib/bootstrap/bootstrap.min.js', 'js/jquery.toc.js', 'js/interface.js', filters="yui_js", output="js/dist/base.js") students_manager_js = Bundle("js/helpers.js", "bower_components/lodash/lodash.min.js", "bower_components/angular/angular.js", "bower_components/angular-route/angular-route.js", "bower_components/angular-animate/angular-animate.js", "js/students/manager/app.js", "js/students/manager/controllers/group.js", "js/students/manager/controllers/groups.js", "js/students/manager/controllers/years.js", "js/students/manager/models/_base.js", "js/students/manager/models/student.js", "js/students/manager/models/group.js", filters="jsmin", output="js/students/manager/dist/app.js") main_css = Bundle('lib/bootstrap/bootstrap.min.css',
def environment(**options): from django.contrib.auth import get_user_model from signup.models import ActivatedUserManager # Hack to install our create_user method. user_class = get_user_model() user_class.objects = ActivatedUserManager() user_class.objects.model = user_class assets_env = get_env() # If we don't force ``auto_reload`` to True, in DEBUG=0, the templates # would only be compiled on the first edit. options.update({'auto_reload': True}) if 'loader' in options: options['loader'] = import_string(options['loader'])( get_template_search_path()) env = DjaoappEnvironment(extensions=[AssetsExtension], **options) # Generic filters to render pages env.filters['asset'] = multitier.templatetags.multitier_tags.asset env.filters['absolute_uri'] = \ multitier.templatetags.multitier_tags.absolute_uri env.filters['djasset'] = djaoapp.templatetags.djaoapp_tags.djasset env.filters['host'] = deployutils_extratags.host env.filters['is_authenticated'] = \ djaoapp.templatetags.djaoapp_tags.is_authenticated env.filters['is_checkbox'] = djaoapp.templatetags.djaoapp_tags.is_checkbox env.filters['is_radio'] = djaoapp.templatetags.djaoapp_tags.is_radio env.filters['is_textarea'] = djaoapp.templatetags.djaoapp_tags.is_textarea env.filters['iterfields'] = djaoapp.templatetags.djaoapp_tags.iterfields env.filters['messages'] = djaoapp.templatetags.djaoapp_tags.messages env.filters['no_cache'] = djaoapp.templatetags.djaoapp_tags.no_cache env.filters['pluralize'] = djaoapp.templatetags.djaoapp_tags.pluralize env.filters['site_prefixed'] = \ multitier.templatetags.multitier_tags.site_prefixed env.filters['to_json'] = deployutils_extratags.to_json # Standard site pages env.filters['site_printable_name'] = \ djaoapp.templatetags.djaoapp_tags.site_printable_name env.filters['url_app'] = djaoapp.templatetags.djaoapp_tags.url_app env.filters['url_contact'] = djaoapp.templatetags.djaoapp_tags.url_contact env.filters['url_home'] = djaoapp.templatetags.djaoapp_tags.url_home env.filters['url_login'] = djaoapp.templatetags.djaoapp_tags.url_login env.filters['url_logout'] = djaoapp.templatetags.djaoapp_tags.url_logout env.filters['url_pricing'] = djaoapp.templatetags.djaoapp_tags.url_pricing env.filters['url_profile'] = djaoapp.templatetags.djaoapp_tags.url_profile env.filters['url_register'] \ = djaoapp.templatetags.djaoapp_tags.url_register # Specific to SaaS env.filters['isoformat'] = saas.templatetags.saas_tags.isoformat env.filters['short_date'] = saas.templatetags.saas_tags.short_date env.filters['humanize_money'] = saas.templatetags.saas_tags.humanize_money env.filters[ 'humanize_period'] = saas.templatetags.saas_tags.humanize_period env.filters['date_in_future'] = saas.templatetags.saas_tags.date_in_future env.filters['md'] = saas.templatetags.saas_tags.md env.filters['describe'] = saas.templatetags.saas_tags.describe if settings.DEBUG: env.filters['query_parameters'] = \ djaoapp.templatetags.djaoapp_tags.query_parameters env.filters['request_body_parameters'] = \ djaoapp.templatetags.djaoapp_tags.request_body_parameters env.filters['not_key'] = \ djaoapp.templatetags.djaoapp_tags.not_key env.filters['schema_href'] = \ djaoapp.templatetags.djaoapp_tags.schema_href env.filters['schema_name'] = \ djaoapp.templatetags.djaoapp_tags.schema_name env.filters['addslashes'] = django.template.defaultfilters.addslashes env.globals.update({ 'FEATURES_DEBUG': settings.FEATURES_DEBUG, 'VUEJS': (settings.JS_FRAMEWORK == 'vuejs'), 'DATETIME_FORMAT': "MMM dd, yyyy", 'url': reverse, 'cycle': django.template.defaulttags.cycle }) env.assets_environment = assets_env return env
def __init__(self, location=None, base_url=None, *args, **kwargs): super(AssetsFileStorage, self).__init__( location or get_env().directory, base_url or get_env().url, *args, **kwargs )
def __init__(self, environment): super(Jinja2AssetsExtension, self).__init__(environment) environment.assets_environment = get_env()
from django_assets import Bundle, register from django_assets.env import get_env get_env().append_path("templates/static") get_env().append_path("excursions/static") main_js = Bundle('bower/jquery/dist/jquery.min.js', 'bower/bootstrap/dist/js/bootstrap.js', 'bower/bootstrap-validator/dist/validator.min.js', 'bower/bootstrap-waitingfor/build/bootstrap-waitingfor.js', 'bower/jquery.cookie/jquery.cookie.js', 'bower/jquery.lazyload/jquery.lazyload.js', 'bower/jquery-impromptu/dist/jquery-impromptu.min.js', 'js/lib/jquery.hypher.js', 'js/lib/jquery.scrollchaser.js', # 'js/lib/modernizr.custom.42386.js', 'js/lib/ru.js', 'js/interface.js', 'js/excursions/main.guest.js', filters="yui_js", output="js/main.min.js") main_css = Bundle('bower/bootstrap/dist/css/bootstrap.min.css', 'bower/jquery-impromptu/dist/jquery-impromptu.min.css', 'css/style.css', 'css/excursions.css', filters="cssmin", output="css/main.min.css") register("main_js", main_js) register("main_css", main_css)
from django_assets import Bundle, register from webassets.filter import register_filter, ExternalTool from django_assets.env import get_env from webassets.filter import Filter from webassets.filter.requirejs import RequireJSFilter get_env().append_path("students/static") # # class MyFilter(ExternalTool): # name = 'myfilter' # options = { # 'module': 'MODULE', # } # # argv = ['r.js', '-o', '{source}'] # method = 'open' # # # register_filter(MyFilter) # f = RequireJSFilter() # f.baseUrl = "js/students/marks" # f.config = "/students/static/js/students/marks/build.js" # marks_js = Bundle('js/students/marks/build.js', # filters=RequireJSFilter(**{'modname': 'marks'}), # output="js/students/marks-built.js") # # register("marks_js", marks_js) #
elif name == 'depends': depends = value # positional arguments are source files elif name is None: files.append(value) else: raise template.TemplateSyntaxError('Unsupported keyword argument "%s"'%name) # capture until closing tag childnodes = parser.parse(("endassets",)) parser.delete_first_token() return AssetsNode(filters, depends, output, debug, files, childnodes) # If Coffin is installed, expose the Jinja2 extension try: from coffin.template import Library as CoffinLibrary except ImportError: register = template.Library() else: register = CoffinLibrary() from webassets.ext.jinja2 import AssetsExtension from django_assets.env import get_env register.tag(AssetsExtension, environment={'assets_environment': get_env()}) # expose the default Django tag register.tag('assets', assets)
ImminentDeprecationWarning) elif name == 'depends': depends = value # positional arguments are source files elif name is None: files.append(value) else: raise template.TemplateSyntaxError( 'Unsupported keyword argument "%s"' % name) # capture until closing tag childnodes = parser.parse(("endassets", )) parser.delete_first_token() return AssetsNode(filters, depends, output, debug, files, childnodes) # If Coffin is installed, expose the Jinja2 extension try: from coffin.template import Library as CoffinLibrary except ImportError: register = template.Library() else: register = CoffinLibrary() from webassets.ext.jinja2 import AssetsExtension from django_assets.env import get_env register.tag(AssetsExtension, environment={'assets_environment': get_env()}) # expose the default Django tag register.tag('assets', assets)