replace(script,
holders,
pattern=None,
as_json=True,
inlined=True,
encoding=None)
| source code
|
Replace javascript values
See fill and fill_attr for more specific usage.
This functions provides safe (single pass) javascript value
replacement:
filled = javascript.replace(script_template, dict(
a=10,
b=u'Andr\xe9',
c=javascript.SimpleJSON(dict(foo='bar')),
))
Where script_template is something like:
// more script...
var count = __a__;
var name = '__b__';
var param = __c__;
// more script...
- Parameters:
script (basestring) - Script content to modify
holders (dict) - Placeholders mappings (name -> value). If a placeholder is found
within the script which has no mapping, it's simply left as-is.
If as_json is true, the values are checked if they have an
as_json method. If they do have one, the method is called
and the result (of type unicode) is used as replacement.
Otherwise the mapped value is piped through the escape_string
function and that result is used as replacement. as_json is
passed a boolean inlined parameter which indicates whether the
method should escape for inline usage or not.
Use the LiteralJSON class for passing any JSON content literally
to the script. There is also a SimpleJSON class for converting
complex structures to JSON using the simplejson converter. You may
pass your own classes as well, of course, as long as they provide
a proper as_json() method.
pattern (unicode or compiled re object) - Placeholder name pattern. If omitted or None, the pattern is
(simplified ): __(?P<name>.+)__, i.e. the placeholder name
enclosed in double-underscores. The name group is expected.
as_json (bool) - Check the placeholder values for an as_json method? See the
description of the holders parameter for details.
inlined (bool) - Escape simple content for being inlined (e.g.
no CDATA endmarkers, </script>).
encoding (str) - Script encoding if script is a str. If omitted or None,
the script is expected to be ASCII compatible.
If script is of type unicode, the encoding is applied to
as_json method return values. This is to make sure, the JSON
stuff is encoded safely. If omitted or None, ASCII is assumed.
JSON result characters not fitting into the this encoding are
escaped (uxxxx).
- Returns: basestring
- The modified script, typed as input
|