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
Provenance
- Commit
f35e281- Tree
a32a51b- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
c2f3a3b
12 files changed+174 added−42 removed
modified:docs/_static/print.css+1 added-2 removed
1234545div.header, div.relnav, #toc { display: none; }#contentwrapper { padding: 0; margin: 0; border: none; }body { color: black; background-color: white; }div.footer { text-align: right; border-top: 1px solid #888; color: #888; margin-top: 1cm; }div.footer { border-top: 1px solid #888; color: #888; margin-top: 1cm; }div.footer a { text-decoration: none; }modified:docs/_static/style.css+15 added-6 removed
6 unmodified lines7 color: #eee;8 }9 10 div.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 }16 17 div.footer a {18 color: #eee;6 unmodified lines25 26 div.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 lines55 padding: 15px 0 0 0;56 }57 58 h1.heading {59- margin: 0 0 0 20px;59+ margin: 0;60 padding: 0;61 height: 80px;62- background: url(jinjabanner.png) no-repeat;62 }63 64+h1.heading:hover {65+ background: #222;66+}67+68 h1.heading a {69+ background: url(jinjabanner.png) no-repeat 20px 0;70 display: block;67- width: 200px;71+ width: 100%;72 height: 80px;73 }74 75+h1.heading a:focus {76+ -moz-outline: none;77+ outline: none;78+}79+80 h1.heading span {81 display: none;82 }83 227 unmodified linesmodified:docs/_static/watermark.pngbinary
A binary file, modified.
modified:docs/_templates/layout.html+2 added-1 removed
43 unmodified lines444546474848495051525322 unmodified lines43 unmodified lines </head> <body> <div id="content"> <div class="header"> <h1 class="heading"><a href="{{ pathto('index') }}"><span>Jinja</span></a></h1> <h1 class="heading"><a href="{{ pathto('index') }}" title="back to the documentation overview"><span>Jinja</span></a></h1> </div> <div class="relnav"> {%- if prev %} <a href="{{ prev.link|e }}">« {{ prev.title }}</a> |22 unmodified linesmodified:docs/api.rst+1 added-1 removed
122 unmodified lines123 The Context124 -----------125 126 .. autoclass:: jinja2.runtime.Context127- :members: super, get, get_exported, get_all127+ :members: resolve, get_exported, get_all128 129 .. attribute:: parent130 131 A dict of read only, global variables the template looks up. These207 unmodified linesmodified:docs/templates.rst+89 added
124 unmodified lines125 ...126 {% endfor %}127 #}128 129+130+Whitespace Control131+------------------132+133+In the default configuration whitespace is not further modified by the134+template engine, so each whitespace (spaces, tabs, newlines etc.) is returned135+unchanged. If the application configures Jinja to `trim_blocks` the first136+newline after a a template tag is removed automatically (like in PHP).137+138+But you can also strip whitespace in templates by hand. If you put an minus139+sign (``-``) to the start or end of an block (for example a for tag), a140+comment or variable expression you can remove the whitespaces after or before141+that block::142+143+ {% for item in seq -%}144+ {{ item }}145+ {%- endfor %}146+ 147+This will yield all elements without whitespace between them. If `seq` was148+a list of numbers from ``1`` to ``9`` the output would be ``123456789``.149+150+Note that you must not use a whitespace between the tag and the minus sign:151+152+ valid:153+ {%- if foo -%}...{% endif %}154+155+ invalid:156+157+ {% - if foo - %}...{% endif %}158+159+If :ref:`line-statements` are enabled they strip leading whitespace160+automatically up to the beginning of the line.161+162+163+Escaping164+--------165+166+It is sometimes desirable or even necessary to have Jinja ignore parts it167+would otherwise handle as variables or blocks. For example if the default168+syntax is used and you want to use ``{{`` as raw string in the template and169+not start a variable you have to use a trick.170+171+The easiest way is to output the variable delimiter (``{{``) by using a172+variable expression::173+174+ {{ '{{' }}175+176+For bigger sections it makes sense to mark a block `raw`. For example to177+put Jinja syntax as example into a template you can use this snippet::178+179+ {% raw %}180+ <ul>181+ {% for item in seq %}182+ <li>{{ item }}</li>183+ {% endfor %}184+ </ul>185+ {% endraw %}186+187+188+.. _line-statements:189+190+Line Statements191+---------------192+193+If line statements are enabled by the application it's possible to mark a194+line as a statement. For example if the line statement prefix is configured195+to ``#`` the following two examples are equivalent::196+197+ <ul>198+ # for item in seq199+ <li>{{ item }}</li>200+ # endfor201+ </ul>202+203+ <ul>204+ {% for item in seq %}205+ <li>{{ item }}</li>206+ {% endfor %}207+ </ul>208+209+The line statement prefix can appear anywhere on the line as long as no text210+precedes it. For better readability statements that start a block (such as211+`for`, `if`, `elif` etc.) may end with a colon::212+213+ # for item in seq:214+ ...215+ # endif216+217+218 .. _template-inheritance:219 220 Template Inheritance221 --------------------713 unmodified linesmodified:jinja2/_speedups.c+21 added-21 removed
21 unmodified lines22 23 static int24 init_constants(void)25 {26- memset(escaped_chars_delta_len, 0, sizeof (escaped_chars_delta_len));27-28- escaped_chars_delta_len['"'] = 5;29- escaped_chars_repl['"'] = UNICHR(""");30-31- escaped_chars_delta_len['&'] = 4;26+ /* happing of characters to replace */27+ escaped_chars_repl['"'] = UNICHR(""");28+ escaped_chars_repl['\''] = UNICHR("'");29 escaped_chars_repl['&'] = UNICHR("&");33- 34- escaped_chars_delta_len['<'] = 3;30 escaped_chars_repl['<'] = UNICHR("<");36- 37- escaped_chars_delta_len['>'] = 3;31 escaped_chars_repl['>'] = UNICHR(">");32+33+ /* 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 lines108 }109 110 111 static PyObject*112-soft_unicode(PyObject *self, PyObject *s)113-{114- if (!PyUnicode_Check(s))115- return PyObject_Unicode(s);116- Py_INCREF(s);117- return s;118-}119-120-121-static PyObject*112 escape(PyObject *self, PyObject *text)113 {114 PyObject *s = NULL, *rv = NULL;115 29 unmodified lines145 return rv;146 }147 148 149+static PyObject*150+soft_unicode(PyObject *self, PyObject *s)151+{152+ if (!PyUnicode_Check(s))153+ return PyObject_Unicode(s);154+ Py_INCREF(s);155+ return s;156+}157+158+159 static PyObject *160 tb_set_next(PyObject *self, PyObject *args)161 {162 PyTracebackObject *tb, *old;23 unmodified lines186 static 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 linesmodified:jinja2/compiler.py+1 added-1 removed
459 unmodified lines460 461 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))465 466 def pull_dependencies(self, nodes):467 """Pull all the dependencies."""468 visitor = DependencyFinderVisitor()774 unmodified linesmodified:jinja2/environment.py+1 added-1 removed
101 unmodified lines102 The string marking the end of a comment. Defaults to ``'#}'``.103 104 `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`.107 108 `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 linesmodified:jinja2/runtime.py+31 added-6 removed
49 unmodified lines50 :func:`contextfunction`\s get the active context passed as first argument51 and are allowed to access the context read-only.52 53 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 """59 60 def __init__(self, environment, parent, name, blocks):61 self.parent = parent34 unmodified lines96 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 default104+105+ 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)114 115 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 lines121 global variables.122 """123 return dict(self.parent, **self.vars)124 125+ 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 proxy131+132+ 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 _all139+140 def __contains__(self, name):141 return name in self.vars or name in self.parent142 143 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)148 149 def __repr__(self):150 return '<%s %s of %r>' % (151 self.__class__.__name__,260 unmodified linesmodified:jinja2/utils.py+11 added-2 removed
301 unmodified lines302 """Strip tags and resolve enities."""303 stripped = u' '.join(_striptags_re.sub('', self).split())304 return Markup(stripped).unescape()305 306+ @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 rv313+314 def make_wrapper(name):315 orig = getattr(unicode, name)316 def func(self, *args, **kwargs):317 args = list(args)167 unmodified lines485 try:486 from jinja2._speedups import escape, soft_unicode487 except 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('&', '&')497 .replace('>', '>')498 .replace('<', '<')499+ .replace("'", ''')500 .replace('"', '"')501 )502 503 def soft_unicode(s):20 unmodified linesmodified:tests/test_filters.py+1 added-1 removed
108 unmodified lines109 110 def test_escape(env):111 tmpl = env.from_string(ESCAPE)112 out = tmpl.render()113- assert out == '<">&'113+ assert out == '<">&'114 115 116 def test_striptags(env):117 tmpl = env.from_string(STRIPTAGS)176 unmodified lines