[svn] doc changes + changes in the i18n system of jinja
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 16d1b1e · Browse files · 10 files·+172 added−21 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
10 files+172 added−21 removed
- other:+172 added−21 removed
Provenance
- Commit
85ddd3b- Tree
53a8c80- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
16d1b1e
10 files changed+172 added−21 removed
modified:docs/src/designerdoc.txt+42 added
491 unmodified lines492 template but outside of a visible block (thus outside of any block) will be493 available in all blocks below. This allows you to use `include` statements to494 load often used macros at once.495 496+Undefined Variables497+===================498+499+If you have already worked with python you probably know about the fact that500+undefined variables raise an exception. This is different in Jinja. There is a501+special value called `undefined` that represents values that do not exist.502+503+This special variable works complete different from any variables you maybe504+know. If you print it using ``{{ variable }}`` it will not appear because it's505+literally empty. If you try to iterate over it, it will work. But no items506+are returned. Comparing this value to any other value results in `false`.507+Even if you compare it to itself:508+509+.. sourcecode:: jinja510+511+ {{ undefined == undefined }}512+ will return false. Not even undefined is undefined :)513+ Use `is defined` / `is not defined`:514+515+ {{ undefined is not defined }}516+ will return true.517+518+There are also some additional rules regarding this special value. Any519+mathematical operators (``+``, ``-``, ``*``, ``/``) return the operand520+as result:521+522+.. sourcecode:: jinja523+524+ {{ undefined + "foo" }}525+ returns "foo"526+527+ {{ undefined - 42 }}528+ returns 42. Note: not -42!529+530+In any expression `undefined` evaluates to `false`. It has no length, all531+attribute calls return undefined, calling too:532+533+.. sourcecode:: jinja534+535+ {{ undefined.attribute().attribute_too[42] }}536+ still returns `undefined`.537+538 Internationalization539 ====================540 541 If the application is configured for i18n, you can define translatable blocks53 unmodified linesmodified:docs/src/index.txt+2 added
23 unmodified lines24 25 - `Syntax Reference <designerdoc.txt>`_26 27 - `Differences To Django <fromdjango.txt>`_28+29+ - `Recipies <recipies.txt>`_added:docs/src/recipies.txt+55 added
1+========2+Recipies3+========4+5+Here are some typical recipes for the usage of Jinja templates.6+7+Alternating Rows8+================9+10+If you want to have different styles for each row of a table or11+list you can use the ``cycle`` tag:12+13+.. sourcecode:: html+jinja14+15+ <ul>16+ {% for row in sequence %}17+ <li class="{% cycle 'even', 'odd' %}">{{ row|e }}</li>18+ {% endfor %}19+ </ul>20+21+``cycle`` can take an unlimited amount of strings. Each time this22+tag is encountered the next item from the list is rendered.23+If you pass it just one argument it's meant to be a sequence.24+25+Active Menu Item26+================27+28+Often you want to have a navigation bar with an active navigation29+item. This is really simple to achieve. Because ``set`` tags outside30+of ``blocks`` are global you can do something like this:31+32+**layout.html**:33+34+ .. sourcecode:: html+jinja35+36+ {% set navigation_bar = [37+ ('/', 'index', 'Index'),38+ ('/downloads/', 'downloads', 'Downloads'),39+ ('/about/', 'about', 'About')40+ ] %}41+ ...42+ <ul id="navigation">43+ {% for href, id, caption in navigation_bar %}44+ <li{% if id == active_page %} class="active"{% endif45+ %}><a href="{{ href|e }}">{{ caption|e }}</a>/li>46+ {% endfor %}47+ </ul>48+ ...49+50+**index.html**:51+52+ .. sourcecode:: jinja53+54+ {% extends "layout.html" %}55+ {% set active_page = "index" %}modified:jinja/translators/python.py+3 added-3 removed
312 unmodified lines313 314 # add translation helpers if required315 if self.require_translations:316 lines.append(317- ' translator = context.get_translator()\n'317+ ' translator = environment.get_translator(context)\n'318 ' def translate(s, p=None, n=None, r=None):\n'319 ' if p is None:\n'320 ' return translator.gettext(s) % (r or {})\n'321 ' return translator.ngettext(s, p, r[n]) % (r or {})'393 unmodified lines715 kwargs[arg.name] = self.handle_node(arg.expr)716 else:717 args.append(self.handle_node(arg))718 if not (args or kwargs or star_args or dstar_args):719- return 'call_function_simple(%s)' % self.handle_node(node.node)720- return 'call_function(%s, %s, {%s}, %s, %s)' % (719+ return 'call_function_simple(%s, context)' % self.handle_node(node.node)720+ return 'call_function(%s, context, %s, {%s}, %s, %s)' % (721 self.handle_node(node.node),722 _to_tuple(args),723 ', '.join(['%r: %s' % i for i in kwargs.iteritems()]),724 star_args,137 unmodified linesmodified:jinja/datastructure.py+23 added-5 removed
16 unmodified lines17 18 from jinja.exceptions import TemplateRuntimeError19 20 21+def contextcallable(f):22+ """23+ Mark a function context callable.24+ """25+ f.jinja_context_callable = True26+ return f27+28+29+def unsafe(f):30+ """31+ Mark function as unsafe.32+ """33+ f.jinja_unsafe_call = True34+ return f35+36+37 class UndefinedType(object):38 """39 An object that does not exist.40 """36 unmodified lines77 def __int__(self):78 return 079 80 def __float__(self):65- return 181+ return 0.082 83+ def __eq__(self, other):84+ return False85+86+ def __ne__(self, other):87+ return True88+89 def __call__(self, *args, **kwargs):90 return self91 92 49 unmodified lines142 143 # cache object used for filters and tests144 self.cache = {}145 124- def get_translator(self):125- """Return the translator for i18n."""126- return FakeTranslator()127-146 def pop(self):147 """Pop the last layer from the stack and return it."""148 rv = self._stack.pop()149 self.current = self._stack[-1]215 unmodified linesmodified:jinja/defaults.py+2 added-2 removed
8 unmodified lines9 :license: BSD, see LICENSE for more details.10 """11 from jinja.filters import FILTERS as DEFAULT_FILTERS12 from jinja.tests import TESTS as DEFAULT_TESTS13-from jinja.utils import debug_context13+from jinja.utils import debug_context, safe_range14 15 16 DEFAULT_NAMESPACE = {17- 'range': range,17+ 'range': safe_range,18 'debug': debug_context19 }modified:jinja/environment.py+19 added-4 removed
10 unmodified lines11 import re12 from jinja.lexer import Lexer13 from jinja.parser import Parser14 from jinja.loaders import LoaderWrapper15-from jinja.datastructure import Undefined, Context, Markup15+from jinja.datastructure import Undefined, Context, Markup, FakeTranslator16 from jinja.utils import escape17 from jinja.exceptions import FilterNotFound, TestNotFound, SecurityException18 from jinja.defaults import DEFAULT_FILTERS, DEFAULT_TESTS, DEFAULT_NAMESPACE19 81 unmodified lines101 return unicode(value)102 except UnicodeError:103 return str(value).decode(self.charset, 'ignore')104 105+ def get_translator(self, context):106+ """107+ Return the translator for i18n.108+109+ A translator is an object that provides the two functions110+ ``gettext(string)`` and ``ngettext(singular, plural, n)``. Note111+ that both of them have to return unicode!112+ """113+ return FakeTranslator()114+115 def apply_filters(self, value, context, filters):116 """117 Apply a list of filters on the variable.118 """40 unmodified lines159 raise SecurityException('unsafe attributed %r accessed' % name)160 node = getattr(node, name)161 return node162 153- def call_function(self, f, args, kwargs, dyn_args, dyn_kwargs):163+ def call_function(self, f, context, args, kwargs, dyn_args, dyn_kwargs):164 """165 Function call helper. Called for all functions that are passed166 any arguments.167 """3 unmodified lines171 kwargs.update(dyn_kwargs)172 if getattr(f, 'jinja_unsafe_call', False) or \173 getattr(f, 'alters_data', False):174 raise SecurityException('unsafe function %r called' % f.__name__)175+ if getattr(f, 'jinja_context_callable', False):176+ args = (self, context) + args177 return f(*args, **kwargs)178 167- def call_function_simple(self, f):179+ def call_function_simple(self, f, context):180 """169- Function call without arguments.181+ Function call without arguments. Because of the smaller signature and182+ fewer logic here we have a bit of redundant code.183 """184 if getattr(f, 'jinja_unsafe_call', False) or \185 getattr(f, 'alters_data', False):186 raise SecurityException('unsafe function %r called' % f.__name__)187+ if getattr(f, 'jinja_context_callable', False):188+ return f(self, context)189 return f()190 191 def finish_var(self, value):192 """13 unmodified linesmodified:jinja/utils.py+22 added-3 removed
21 unmodified lines22 from collections import deque23 except ImportError:24 deque = None25 26+#: number of maximal range items27+MAX_RANGE = 100000028+29 _debug_info_re = re.compile(r'^\s*\# DEBUG\(filename=(.*?), lineno=(.*?)\)$')30 31 _escape_pairs = {32 '&': '&',87 unmodified lines120 yield node.lineno, node.singular, node.plural121 queue.extend(node.getChildNodes())122 123 121-def debug_context():124+def debug_context(env, context):125 """126 Use this function in templates to get a printed context.124- Use this only in templates because it touches the stack.127 """126- context = sys._getframe(2).f_locals['context']128 from pprint import pformat129 return pformat(context.to_dict())130+debug_context.jinja_context_callable = True131 132 133+def safe_range(start, stop=None, step=None):134+ """135+ "Safe" form of range that does not generate too large lists.136+ """137+ # this also works with None since None is always smaller than138+ # any other value.139+ if start > MAX_RANGE:140+ start = MAX_RANGE141+ if stop > MAX_RANGE:142+ stop = MAX_RANGE143+ if step is None:144+ step = 1145+ if stop is None:146+ return range(0, start, step)147+ return range(start, stop, step)148+149+150 # python2.4 and lower has a bug regarding joining of broken generators151 if sys.hexversion < (2, 5):152 def capture_generator(gen):153 """210 unmodified linesmodified:www/download.html+1 added-1 removed
24 unmodified lines25 If you want to install the release with26 <a href="http://peak.telecommunity.com/DevCenter/EasyInstall">easy_install</a>,27 you can do it using this command:28 </p>29- <pre>easy_install Pygments</pre>29+ <pre>easy_install Jinja</pre>30 <p>31 You can also get the development source from subversion using this command:32 </p>33 <pre>svn co http://trac.pocoo.org/repos/jinja/trunk jinja</pre>16 unmodified linesmodified:www/index.html+3 added-3 removed
38 unmodified lines39 <span class="cp">{%</span> <span class="k">endfor</span> <span class="cp">%}</span>40 <span class="nt"></ul></span>41 <span class="cp">{%</span> <span class="k">endblock</span> <span class="cp">%}</span>42 </pre></div>43- <h2>Philosphy</h2>43+ <h2>Philosophy</h2>44 <p>45- Application logic is for the controller but don't try to make the live for the46- template designer too hard by giving him too less functionality.45+ Application logic is for the controller but don't try to make the life for the46+ template designer too hard by giving him too few functionality.47 </p>48 <h2>Features</h2>49 <ul>50 <li><strong>Simple API</strong>. For basic usage just one function is needed:39 unmodified lines