Skip to content

Commit 0d6ea78

Browse files
michaeljonesowais
authored andcommitted
Create util functions from templatetags code (django-webpack#96)
Rather than doing the work in the template tags, we do the work in utils functions so that the same functionality is available directly to Python application code. This can be useful for `media` properties on Django widgets (django-webpack#95). The README has been updated to provide simple examples of usage.
1 parent c858d50 commit 0d6ea78

File tree

3 files changed

+81
-37
lines changed

3 files changed

+81
-37
lines changed

README.md

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -295,6 +295,20 @@ In the below example, `logo.png` can be any static asset shipped with any npm or
295295
296296
<br>
297297
298+
### From Python code
299+
300+
If you want to access the webpack asset path information from your application code then you can use
301+
the function in the `webpack_loader.utils` module.
302+
303+
```python
304+
>>> utils.get_files('main')
305+
[{'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'},
306+
{'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'}]
307+
>>> utils.get_as_tags('main')
308+
['<script type="text/javascript" src="/static/bundles/main.js" ></script>',
309+
'<link type="text/css" href="/static/bundles/styles.css" rel="stylesheet" />']
310+
311+
298312
## How to use in Production
299313
300314
**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.

webpack_loader/templatetags/webpack_loader.py

Lines changed: 5 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -2,52 +2,20 @@
22
from django.conf import settings
33
from django.utils.safestring import mark_safe
44

5-
from ..utils import get_loader
5+
from .. import utils
66

77
register = template.Library()
88

99

10-
def filter_by_extension(bundle, extension):
11-
'''Return only files with the given extension'''
12-
for chunk in bundle:
13-
if chunk['name'].endswith('.{0}'.format(extension)):
14-
yield chunk
15-
16-
17-
def render_as_tags(bundle, attrs):
18-
tags = []
19-
for chunk in bundle:
20-
if chunk['name'].endswith(('.js', '.js.gz')):
21-
tags.append((
22-
'<script type="text/javascript" src="{0}" {1}></script>'
23-
).format(chunk['url'], attrs))
24-
elif chunk['name'].endswith(('.css', '.css.gz')):
25-
tags.append((
26-
'<link type="text/css" href="{0}" rel="stylesheet" {1}/>'
27-
).format(chunk['url'], attrs))
28-
return mark_safe('\n'.join(tags))
29-
30-
31-
def _get_bundle(bundle_name, extension, config):
32-
bundle = get_loader(config).get_bundle(bundle_name)
33-
if extension:
34-
bundle = filter_by_extension(bundle, extension)
35-
return bundle
36-
37-
3810
@register.simple_tag
3911
def render_bundle(bundle_name, extension=None, config='DEFAULT', attrs=''):
40-
return render_as_tags(_get_bundle(bundle_name, extension, config), attrs)
12+
tags = utils.get_as_tags(bundle_name, extension=extension, config=config, attrs=attrs)
13+
return mark_safe('\n'.join(tags))
4114

4215

4316
@register.simple_tag
4417
def webpack_static(asset_name, config='DEFAULT'):
45-
return "{0}{1}".format(
46-
get_loader(config).get_assets().get(
47-
'publicPath', getattr(settings, 'STATIC_URL')
48-
),
49-
asset_name
50-
)
18+
return utils.get_static(asset_name, config=config)
5119

5220

5321
assignment_tag = register.simple_tag if VERSION >= (1, 9) else register.assignment_tag
@@ -65,4 +33,4 @@ def get_files(bundle_name, extension=None, config='DEFAULT'):
6533
:param config: (optional) the name of the configuration
6634
:return: a list of matching chunks
6735
"""
68-
return list(_get_bundle(bundle_name, extension, config))
36+
return utils.get_files(bundle_name, extension=extension, config=config)

webpack_loader/utils.py

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
from django.conf import settings
2+
13
from .loader import WebpackLoader
24

35

@@ -8,3 +10,63 @@ def get_loader(config_name):
810
if config_name not in _loaders:
911
_loaders[config_name] = WebpackLoader(config_name)
1012
return _loaders[config_name]
13+
14+
15+
def _filter_by_extension(bundle, extension):
16+
'''Return only files with the given extension'''
17+
for chunk in bundle:
18+
if chunk['name'].endswith('.{0}'.format(extension)):
19+
yield chunk
20+
21+
22+
def _get_bundle(bundle_name, extension, config):
23+
bundle = get_loader(config).get_bundle(bundle_name)
24+
if extension:
25+
bundle = _filter_by_extension(bundle, extension)
26+
return bundle
27+
28+
29+
def get_files(bundle_name, extension=None, config='DEFAULT'):
30+
'''Returns list of chunks from named bundle'''
31+
return list(_get_bundle(bundle_name, extension, config))
32+
33+
34+
def get_as_tags(bundle_name, extension=None, config='DEFAULT', attrs=''):
35+
'''
36+
Get a list of formatted <script> & <link> tags for the assets in the
37+
named bundle.
38+
39+
:param bundle_name: The name of the bundle
40+
:param extension: (optional) filter by extension, eg. 'js' or 'css'
41+
:param config: (optional) the name of the configuration
42+
:return: a list of formatted tags as strings
43+
'''
44+
45+
bundle = _get_bundle(bundle_name, extension, config)
46+
tags = []
47+
for chunk in bundle:
48+
if chunk['name'].endswith(('.js', '.js.gz')):
49+
tags.append((
50+
'<script type="text/javascript" src="{0}" {1}></script>'
51+
).format(chunk['url'], attrs))
52+
elif chunk['name'].endswith(('.css', '.css.gz')):
53+
tags.append((
54+
'<link type="text/css" href="{0}" rel="stylesheet" {1}/>'
55+
).format(chunk['url'], attrs))
56+
return tags
57+
58+
59+
def get_static(asset_name, config='DEFAULT'):
60+
'''
61+
Equivalent to Django's 'static' look up but for webpack assets.
62+
63+
:param asset_name: the name of the asset
64+
:param config: (optional) the name of the configuration
65+
:return: path to webpack asset as a string
66+
'''
67+
return "{0}{1}".format(
68+
get_loader(config).get_assets().get(
69+
'publicPath', getattr(settings, 'STATIC_URL')
70+
),
71+
asset_name
72+
)

0 commit comments

Comments
 (0)