Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -295,6 +295,20 @@ In the below example, `logo.png` can be any static asset shipped with any npm or

<br>

### From Python code

If you want to access the webpack asset path information from your application code then you can use
the function in the `webpack_loader.utils` module.

```python
>>> utils.get_files('main')
[{'url': '/static/bundles/main.js', u'path': u'/home/mike/root/projects/django-webpack-loader/tests/assets/bundles/main.js', u'name': u'main.js'},
{'url': '/static/bundles/styles.css', u'path': u'/home/mike/root/projects/django-webpack-loader/tests/assets/bundles/styles.css', u'name': u'styles.css'}]
>>> utils.get_as_tags('main')
['<script type="text/javascript" src="/static/bundles/main.js" ></script>',
'<link type="text/css" href="/static/bundles/styles.css" rel="stylesheet" />']


## How to use in Production

**It is up to you**. There are a few ways to handle this. I like to have slightly separate configs for production and local. I tell git to ignore my local stats + bundle file but track the ones for production. Before pushing out newer version to production, I generate a new bundle using production config and commit the new stats file and bundle. I store the stats file and bundles in a directory that is added to the `STATICFILES_DIR`. This gives me integration with collectstatic for free. The generated bundles are automatically collected to the target directory and synched to S3.
Expand Down
42 changes: 5 additions & 37 deletions webpack_loader/templatetags/webpack_loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,52 +2,20 @@
from django.conf import settings
from django.utils.safestring import mark_safe

from ..utils import get_loader
from .. import utils

register = template.Library()


def filter_by_extension(bundle, extension):
'''Return only files with the given extension'''
for chunk in bundle:
if chunk['name'].endswith('.{0}'.format(extension)):
yield chunk


def render_as_tags(bundle, attrs):
tags = []
for chunk in bundle:
if chunk['name'].endswith(('.js', '.js.gz')):
tags.append((
'<script type="text/javascript" src="{0}" {1}></script>'
).format(chunk['url'], attrs))
elif chunk['name'].endswith(('.css', '.css.gz')):
tags.append((
'<link type="text/css" href="{0}" rel="stylesheet" {1}/>'
).format(chunk['url'], attrs))
return mark_safe('\n'.join(tags))


def _get_bundle(bundle_name, extension, config):
bundle = get_loader(config).get_bundle(bundle_name)
if extension:
bundle = filter_by_extension(bundle, extension)
return bundle


@register.simple_tag
def render_bundle(bundle_name, extension=None, config='DEFAULT', attrs=''):
return render_as_tags(_get_bundle(bundle_name, extension, config), attrs)
tags = utils.get_as_tags(bundle_name, extension=extension, config=config, attrs=attrs)
return mark_safe('\n'.join(tags))


@register.simple_tag
def webpack_static(asset_name, config='DEFAULT'):
return "{0}{1}".format(
get_loader(config).get_assets().get(
'publicPath', getattr(settings, 'STATIC_URL')
),
asset_name
)
return utils.get_static(asset_name, config=config)


assignment_tag = register.simple_tag if VERSION >= (1, 9) else register.assignment_tag
Expand All @@ -65,4 +33,4 @@ def get_files(bundle_name, extension=None, config='DEFAULT'):
:param config: (optional) the name of the configuration
:return: a list of matching chunks
"""
return list(_get_bundle(bundle_name, extension, config))
return utils.get_files(bundle_name, extension=extension, config=config)
62 changes: 62 additions & 0 deletions webpack_loader/utils.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from django.conf import settings

from .loader import WebpackLoader


Expand All @@ -8,3 +10,63 @@ def get_loader(config_name):
if config_name not in _loaders:
_loaders[config_name] = WebpackLoader(config_name)
return _loaders[config_name]


def _filter_by_extension(bundle, extension):
'''Return only files with the given extension'''
for chunk in bundle:
if chunk['name'].endswith('.{0}'.format(extension)):
yield chunk


def _get_bundle(bundle_name, extension, config):
bundle = get_loader(config).get_bundle(bundle_name)
if extension:
bundle = _filter_by_extension(bundle, extension)
return bundle


def get_files(bundle_name, extension=None, config='DEFAULT'):
'''Returns list of chunks from named bundle'''
return list(_get_bundle(bundle_name, extension, config))


def get_as_tags(bundle_name, extension=None, config='DEFAULT', attrs=''):
'''
Get a list of formatted <script> & <link> tags for the assets in the
named bundle.

:param bundle_name: The name of the bundle
:param extension: (optional) filter by extension, eg. 'js' or 'css'
:param config: (optional) the name of the configuration
:return: a list of formatted tags as strings
'''

bundle = _get_bundle(bundle_name, extension, config)
tags = []
for chunk in bundle:
if chunk['name'].endswith(('.js', '.js.gz')):
tags.append((
'<script type="text/javascript" src="{0}" {1}></script>'
).format(chunk['url'], attrs))
elif chunk['name'].endswith(('.css', '.css.gz')):
tags.append((
'<link type="text/css" href="{0}" rel="stylesheet" {1}/>'
).format(chunk['url'], attrs))
return tags


def get_static(asset_name, config='DEFAULT'):
'''
Equivalent to Django's 'static' look up but for webpack assets.

:param asset_name: the name of the asset
:param config: (optional) the name of the configuration
:return: path to webpack asset as a string
'''
return "{0}{1}".format(
get_loader(config).get_assets().get(
'publicPath', getattr(settings, 'STATIC_URL')
),
asset_name
)