This repository has been archived by the owner on Nov 27, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 12
/
render_utils.py
177 lines (127 loc) · 4.36 KB
/
render_utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
#!/usr/bin/env python
from cssmin import cssmin
from flask import Markup, g, render_template, request
from slimit import minify
import app_config
import copytext
CSS_HEADER = '''
/*
* Looking for the full, uncompressed source? Try here:
*
* https://github.com/nprapps/%s
*/
''' % app_config.REPOSITORY_NAME
JS_HEADER = '''
/*
* Looking for the full, uncompressed source? Try here:
*
* https://github.com/nprapps/%s
*/
''' % app_config.REPOSITORY_NAME
class Includer(object):
"""
Base class for Javascript and CSS psuedo-template-tags.
"""
def __init__(self):
self.includes = []
self.tag_string = None
def push(self, path):
self.includes.append(path)
return ""
def _compress(self):
raise NotImplementedError()
def _relativize_path(self, path):
relative_path = path
depth = len(request.path.split('/')) - 2
while depth > 0:
relative_path = '../%s' % relative_path
depth -= 1
return relative_path
def render(self, path, **kwargs):
if getattr(g, 'compile_includes', False):
out_filename = 'www/%s' % path
if out_filename not in g.compiled_includes:
print 'Rendering %s' % out_filename
with open(out_filename, 'w') as f:
f.write(self._compress())
# See "fab render"
g.compiled_includes.append(out_filename)
kwargs['path'] = self._relativize_path(path)
markup = Markup(self.tag_string % kwargs)
else:
response = []
for src in self.includes:
kwargs['path'] = self._relativize_path(src)
response.append(self.tag_string % kwargs)
response = '\n'.join(response)
markup = Markup(response)
del self.includes[:]
return markup
class JavascriptIncluder(Includer):
"""
Psuedo-template tag that handles collecting Javascript and serving appropriate clean or compressed versions.
"""
def __init__(self):
Includer.__init__(self)
self.tag_string = '<script type="text/javascript" src="%(path)s"></script>'
def _compress(self):
output = []
src_paths = []
for src in self.includes:
src_paths.append('www/%s' % src)
with open('www/%s' % src) as f:
print '- compressing %s' % src
output.append(minify(f.read()))
context = make_context()
context['paths'] = src_paths
header = render_template('_js_header.js', **context)
output.insert(0, header)
return '\n'.join(output)
class CSSIncluder(Includer):
"""
Psuedo-template tag that handles collecting CSS and serving appropriate clean or compressed versions.
"""
def __init__(self):
Includer.__init__(self)
self.tag_string = '<link rel="stylesheet" type="text/css" href="%(path)s" media="%(media)s" />'
def _compress(self):
output = []
src_paths = []
for src in self.includes:
if src.endswith('less'):
src_paths.append('%s' % src)
src = src.replace('less', 'css') # less/example.less -> css/example.css
src = '%s.less.css' % src[:-4] # css/example.css -> css/example.less.css
else:
src_paths.append('www/%s' % src)
with open('www/%s' % src) as f:
print '- compressing %s' % src
output.append(cssmin(f.read()))
context = make_context()
context['paths'] = src_paths
header = render_template('_css_header.css', **context)
output.insert(0, header)
return '\n'.join(output)
def set_media(media):
self.media = media
def flatten_app_config():
"""
Returns a copy of app_config containing only
configuration variables.
"""
config = {}
# Only all-caps [constant] vars get included
for k, v in app_config.__dict__.items():
if k.upper() == k:
config[k] = v
return config
def make_context():
"""
Create a base-context for rendering views.
Includes app_config and JS/CSS includers.
"""
context = flatten_app_config()
context['COPY'] = copytext.Copy()
context['JS'] = JavascriptIncluder()
context['CSS'] = CSSIncluder()
return context