Skip to content

Commit

Permalink
"Merge pull request #461 from Kazade/master\n\nAdd a ReplaceFilter fo…
Browse files Browse the repository at this point in the history
…r search/replacing strings"
  • Loading branch information
miracle2k committed May 17, 2016
2 parents 854efd1 + 15c1f1f commit 885ba2b
Showing 1 changed file with 52 additions and 0 deletions.
52 changes: 52 additions & 0 deletions src/webassets/filter/replace.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import re
from webassets.filter import (
Filter,
register_filter
)


class ReplaceFilter(Filter):
"""
A filter that allows arbitrary search/replace of strings using a source
regex and a replacement string. Unlike cssrewrite this works on strings
which are not paths and can be used as an output filter.
Usage:
replace_static_urls = ReplaceFilter(
pattern=r'\s*{{\s*STATIC_URL\s*}}\s*',
repl=settings.STATIC_URL,
)
"""

name = 'replace'
max_debug_level = None

def __init__(self, pattern=None, repl=None, as_output=True, **kwargs):
self.pattern = pattern
self.repl = repl
self.as_output = as_output

super(ReplaceFilter, self).__init__(**kwargs)

def unique(self):
""" Return a hashable representation of the parameters to allow different instances of this filter. """
return self.pattern, self.repl

def _process(self, _in, out, **kwargs):
out.write(re.sub(self.pattern, self.repl, _in.read()))

def output(self, _in, out, **kwargs):
if self.as_output:
self._process(_in, out, **kwargs)
else:
out.write(_in.read())

def input(self, _in, out, **kwargs):
if self.as_output:
out.write(_in.read())
else:
self._process(_in, out, **kwargs)


register_filter(ReplaceFilter)

0 comments on commit 885ba2b

Please sign in to comment.