Skip to content
Myr

some documentation improvements, jinja escapes " and ' now, both into charpoints and no named entities for html 3.2 support ;-)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

--HG-- branch : trunk

authored by Armin Ronacher · committed by Armin Ronacher · parent c2f3a3b · Browse files · 12 files+174 added−42 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

12 files+174 added−42 removed

  • tests:+1 added−1 removed
  • other:+173 added−41 removed

12 files+174 added−42 removed

modified:docs/_static/print.css+1 added-2 removed
modified:docs/_static/style.css+15 added-6 removed
6 unmodified lines
7 color: #eee;8}910div.footer {11 border-top: 1px solid #111;11 border-top: 1px solid black;12 padding: 8px;13 font-size: 11px;14 text-align: center;14 text-align: right;15}1617div.footer a {18 color: #eee;
6 unmodified lines
2526div.relnav {27 border-bottom: 1px solid #ACACAC;28 background: url(navigation.png);29 padding: 2px 20px 0 38px;29 padding: 2px 20px 0 28px;30 line-height: 25px;31 color: #aaa;32 font-size: 12px;33}
21 unmodified lines
55 padding: 15px 0 0 0;56}5758h1.heading {59 margin: 0 0 0 20px;59 margin: 0;60 padding: 0;61 height: 80px;62 background: url(jinjabanner.png) no-repeat;62}6364h1.heading:hover {65 background: #222;66}6768h1.heading a {69 background: url(jinjabanner.png) no-repeat 20px 0;70 display: block;67 width: 200px;71 width: 100%;72 height: 80px;73}7475h1.heading a:focus {76 -moz-outline: none;77 outline: none;78}7980h1.heading span {81 display: none;82}83
227 unmodified lines
modified:docs/_static/watermark.pngbinary

A binary file, modified.

modified:docs/_templates/layout.html+2 added-1 removed
modified:docs/api.rst+1 added-1 removed
122 unmodified lines
123The Context124-----------125126.. autoclass:: jinja2.runtime.Context127 :members: super, get, get_exported, get_all127 :members: resolve, get_exported, get_all128129 .. attribute:: parent130131 A dict of read only, global variables the template looks up. These
207 unmodified lines
modified:docs/templates.rst+89 added
124 unmodified lines
125 ...126 {% endfor %}127 #}128129130Whitespace Control131------------------132133In the default configuration whitespace is not further modified by the134template engine, so each whitespace (spaces, tabs, newlines etc.) is returned135unchanged. If the application configures Jinja to `trim_blocks` the first136newline after a a template tag is removed automatically (like in PHP).137138But you can also strip whitespace in templates by hand. If you put an minus139sign (``-``) to the start or end of an block (for example a for tag), a140comment or variable expression you can remove the whitespaces after or before141that block::142143 {% for item in seq -%}144 {{ item }}145 {%- endfor %}146 147This will yield all elements without whitespace between them. If `seq` was148a list of numbers from ``1`` to ``9`` the output would be ``123456789``.149150Note that you must not use a whitespace between the tag and the minus sign:151152 valid:153 {%- if foo -%}...{% endif %}154155 invalid:156157 {% - if foo - %}...{% endif %}158159If :ref:`line-statements` are enabled they strip leading whitespace160automatically up to the beginning of the line.161162163Escaping164--------165166It is sometimes desirable or even necessary to have Jinja ignore parts it167would otherwise handle as variables or blocks. For example if the default168syntax is used and you want to use ``{{`` as raw string in the template and169not start a variable you have to use a trick.170171The easiest way is to output the variable delimiter (``{{``) by using a172variable expression::173174 {{ '{{' }}175176For bigger sections it makes sense to mark a block `raw`. For example to177put Jinja syntax as example into a template you can use this snippet::178179 {% raw %}180 <ul>181 {% for item in seq %}182 <li>{{ item }}</li>183 {% endfor %}184 </ul>185 {% endraw %}186187188.. _line-statements:189190Line Statements191---------------192193If line statements are enabled by the application it's possible to mark a194line as a statement. For example if the line statement prefix is configured195to ``#`` the following two examples are equivalent::196197 <ul>198 # for item in seq199 <li>{{ item }}</li>200 # endfor201 </ul>202203 <ul>204 {% for item in seq %}205 <li>{{ item }}</li>206 {% endfor %}207 </ul>208209The line statement prefix can appear anywhere on the line as long as no text210precedes it. For better readability statements that start a block (such as211`for`, `if`, `elif` etc.) may end with a colon::212213 # for item in seq:214 ...215 # endif216217218.. _template-inheritance:219220Template Inheritance221--------------------
713 unmodified lines
modified:jinja2/_speedups.c+21 added-21 removed
21 unmodified lines
2223static int24init_constants(void)25{26 memset(escaped_chars_delta_len, 0, sizeof (escaped_chars_delta_len));2728 escaped_chars_delta_len['"'] = 5;29 escaped_chars_repl['"'] = UNICHR("&quot;");3031 escaped_chars_delta_len['&'] = 4;26 /* happing of characters to replace */27 escaped_chars_repl['"'] = UNICHR("&#34;");28 escaped_chars_repl['\''] = UNICHR("&#39;");29 escaped_chars_repl['&'] = UNICHR("&amp;");33 34 escaped_chars_delta_len['<'] = 3;30 escaped_chars_repl['<'] = UNICHR("&lt;");36 37 escaped_chars_delta_len['>'] = 3;31 escaped_chars_repl['>'] = UNICHR("&gt;");3233 /* lengths of those characters when replaced - 1 */34 memset(escaped_chars_delta_len, 0, sizeof (escaped_chars_delta_len));35 escaped_chars_delta_len['"'] = escaped_chars_delta_len['\''] = \36 escaped_chars_delta_len['&'] = 4;37 escaped_chars_delta_len['<'] = escaped_chars_delta_len['>'] = 3;38 39 /* import markup type so that we can mark the return value */40 PyObject *module = PyImport_ImportModule("jinja2.utils");41 if (!module)42 return 0;43 markup = PyObject_GetAttrString(module, "Markup");
64 unmodified lines
108}109110111static PyObject*112soft_unicode(PyObject *self, PyObject *s)113{114 if (!PyUnicode_Check(s))115 return PyObject_Unicode(s);116 Py_INCREF(s);117 return s;118}119120121static PyObject*112escape(PyObject *self, PyObject *text)113{114 PyObject *s = NULL, *rv = NULL;115
29 unmodified lines
145 return rv;146}147148149static PyObject*150soft_unicode(PyObject *self, PyObject *s)151{152 if (!PyUnicode_Check(s))153 return PyObject_Unicode(s);154 Py_INCREF(s);155 return s;156}157158159static PyObject *160tb_set_next(PyObject *self, PyObject *args)161{162 PyTracebackObject *tb, *old;
23 unmodified lines
186static PyMethodDef module_methods[] = {187 {"escape", (PyCFunction)escape, METH_O,188 "escape(s) -> markup\n\n"189 "Convert the characters &, <, >, and \" in string s to HTML-safe\n"190 "sequences. Use this if you need to display text that might contain\n"190 "sequences. Use this if you need to display text that might contain\n"191 "such characters in HTML. Marks return value as markup string."},192 {"soft_unicode", (PyCFunction)soft_unicode, METH_O,193 "soft_unicode(object) -> string\n\n"194 "Make a string unicode if it isn't already. That way a markup\n"
18 unmodified lines
modified:jinja2/compiler.py+1 added-1 removed
459 unmodified lines
460461 def pull_locals(self, frame):462 """Pull all the references identifiers into the local scope."""463 for name in frame.identifiers.undeclared:464 self.writeline('l_%s = context[%r]' % (name, name))464 self.writeline('l_%s = context.resolve(%r)' % (name, name))465466 def pull_dependencies(self, nodes):467 """Pull all the dependencies."""468 visitor = DependencyFinderVisitor()
774 unmodified lines
modified:jinja2/environment.py+1 added-1 removed
101 unmodified lines
102 The string marking the end of a comment. Defaults to ``'#}'``.103104 `line_statement_prefix`105 If given and a string, this will be used as prefix for line based106 statements.106 statements. See also :ref:`line-statements`.107108 `trim_blocks`109 If this is set to ``True`` the first newline after a block is110 removed (block, not variable tag!). Defaults to `False`.
563 unmodified lines
modified:jinja2/runtime.py+31 added-6 removed
49 unmodified lines
50 :func:`contextfunction`\s get the active context passed as first argument51 and are allowed to access the context read-only.5253 The template context supports read only dict operations (`get`,54 `__getitem__`, `__contains__`) however `__getitem__` doesn't fail with55 a `KeyError` but returns an :attr:`Undefined` object.54 `keys`, `values`, `items`, `iterkeys`, `itervalues`, `iteritems`,55 `__getitem__`, `__contains__`). Additionally there is a :meth:`resolve`56 method that doesn't fail with a `KeyError` but returns an57 :class:`Undefined` object for missing variables.58 """5960 def __init__(self, environment, parent, name, blocks):61 self.parent = parent
34 unmodified lines
96 def get(self, key, default=None):97 """Returns an item from the template context, if it doesn't exist98 `default` is returned.99 """100 try:101 return self[key]102 except KeyError:103 return default104105 def resolve(self, key):106 """Looks up a variable like `__getitem__` or `get` but returns an107 :class:`Undefined` object with the name of the name looked up.108 """109 if key in self.vars:110 return self.vars[key]111 if key in self.parent:112 return self.parent[key]102 return default113 return self.environment.undefined(name=key)114115 def get_exported(self):116 """Get a new dict with the exported variables."""117 return dict((k, self.vars[k]) for k in self.exported_vars)
3 unmodified lines
121 global variables.122 """123 return dict(self.parent, **self.vars)124125 def _all(meth):126 def proxy(self):127 return getattr(self.get_all(), meth)()128 proxy.__doc__ = getattr(dict, meth).__doc__129 proxy.__name__ = meth130 return proxy131132 keys = _all('keys')133 values = _all('values')134 items = _all('items')135 iterkeys = _all('iterkeys')136 itervalues = _all('itervalues')137 iteritems = _all('iteritems')138 del _all139140 def __contains__(self, name):141 return name in self.vars or name in self.parent142143 def __getitem__(self, key):144 """Lookup a variable or raise `KeyError`."""145 if key in self.vars:146 return self.vars[key]120 if key in self.parent:121 return self.parent[key]147 return self.parent[key]122 return self.environment.undefined(name=key)148149 def __repr__(self):150 return '<%s %s of %r>' % (151 self.__class__.__name__,
260 unmodified lines
modified:jinja2/utils.py+11 added-2 removed
301 unmodified lines
302 """Strip tags and resolve enities."""303 stripped = u' '.join(_striptags_re.sub('', self).split())304 return Markup(stripped).unescape()305306 @classmethod307 def escape(cls, s):308 """Escape the string. Works like :func:`escape`."""309 rv = escape(s)310 if rv.__class__ is not cls:311 return cls(rv)312 return rv313314 def make_wrapper(name):315 orig = getattr(unicode, name)316 def func(self, *args, **kwargs):317 args = list(args)
167 unmodified lines
485try:486 from jinja2._speedups import escape, soft_unicode487except ImportError:488 def escape(s):481 """Convert the characters &, <, >, and " in string s to HTML-safe482 sequences. Use this if you need to display text that might contain489 """Convert the characters &, <, >, ' and " in string s to HTML-safe490 sequences. Use this if you need to display text that might contain491 such characters in HTML. Marks return value as markup string.492 """493 if hasattr(s, '__html__'):494 return s.__html__()495 return Markup(unicode(s)496 .replace('&', '&amp;')497 .replace('>', '&gt;')498 .replace('<', '&lt;')499 .replace("'", '&#39;')500 .replace('"', '&quot;')501 )502503 def soft_unicode(s):
20 unmodified lines
modified:tests/test_filters.py+1 added-1 removed
108 unmodified lines
109110def test_escape(env):111 tmpl = env.from_string(ESCAPE)112 out = tmpl.render()113 assert out == '&lt;&quot;&gt;&amp;'113 assert out == '&lt;&#34;&gt;&amp;'114115116def test_striptags(env):117 tmpl = env.from_string(STRIPTAGS)
176 unmodified lines