Skip to content
Myr

[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

10 files+172 added−21 removed

modified:docs/src/designerdoc.txt+42 added
491 unmodified lines
492template but outside of a visible block (thus outside of any block) will be493available in all blocks below. This allows you to use `include` statements to494load often used macros at once.495496Undefined Variables497===================498499If you have already worked with python you probably know about the fact that500undefined variables raise an exception. This is different in Jinja. There is a501special value called `undefined` that represents values that do not exist.502503This special variable works complete different from any variables you maybe504know. If you print it using ``{{ variable }}`` it will not appear because it's505literally empty. If you try to iterate over it, it will work. But no items506are returned. Comparing this value to any other value results in `false`.507Even if you compare it to itself:508509.. sourcecode:: jinja510511 {{ undefined == undefined }}512 will return false. Not even undefined is undefined :)513 Use `is defined` / `is not defined`:514515 {{ undefined is not defined }}516 will return true.517518There are also some additional rules regarding this special value. Any519mathematical operators (``+``, ``-``, ``*``, ``/``) return the operand520as result:521522.. sourcecode:: jinja523524 {{ undefined + "foo" }}525 returns "foo"526527 {{ undefined - 42 }}528 returns 42. Note: not -42!529530In any expression `undefined` evaluates to `false`. It has no length, all531attribute calls return undefined, calling too:532533.. sourcecode:: jinja534535 {{ undefined.attribute().attribute_too[42] }}536 still returns `undefined`.537538Internationalization539====================540541If the application is configured for i18n, you can define translatable blocks
53 unmodified lines
modified:docs/src/index.txt+2 added
23 unmodified lines
2425 - `Syntax Reference <designerdoc.txt>`_2627 - `Differences To Django <fromdjango.txt>`_2829 - `Recipies <recipies.txt>`_
added:docs/src/recipies.txt+55 added
1========2Recipies3========45Here are some typical recipes for the usage of Jinja templates.67Alternating Rows8================910If you want to have different styles for each row of a table or11list you can use the ``cycle`` tag:1213.. sourcecode:: html+jinja1415 <ul>16 {% for row in sequence %}17 <li class="{% cycle 'even', 'odd' %}">{{ row|e }}</li>18 {% endfor %}19 </ul>2021``cycle`` can take an unlimited amount of strings. Each time this22tag is encountered the next item from the list is rendered.23If you pass it just one argument it's meant to be a sequence.2425Active Menu Item26================2728Often you want to have a navigation bar with an active navigation29item. This is really simple to achieve. Because ``set`` tags outside30of ``blocks`` are global you can do something like this:3132**layout.html**:3334 .. sourcecode:: html+jinja3536 {% 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 ...4950**index.html**:5152 .. sourcecode:: jinja5354 {% extends "layout.html" %}55 {% set active_page = "index" %}
modified:jinja/translators/python.py+3 added-3 removed
312 unmodified lines
313314 # 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 lines
715 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 lines
modified:jinja/datastructure.py+23 added-5 removed
16 unmodified lines
1718from jinja.exceptions import TemplateRuntimeError192021def contextcallable(f):22 """23 Mark a function context callable.24 """25 f.jinja_context_callable = True26 return f272829def unsafe(f):30 """31 Mark function as unsafe.32 """33 f.jinja_unsafe_call = True34 return f353637class UndefinedType(object):38 """39 An object that does not exist.40 """
36 unmodified lines
77 def __int__(self):78 return 07980 def __float__(self):65 return 181 return 0.08283 def __eq__(self, other):84 return False8586 def __ne__(self, other):87 return True8889 def __call__(self, *args, **kwargs):90 return self9192
49 unmodified lines
142143 # cache object used for filters and tests144 self.cache = {}145124 def get_translator(self):125 """Return the translator for i18n."""126 return FakeTranslator()127146 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 lines
modified:jinja/defaults.py+2 added-2 removed
8 unmodified lines
9 :license: BSD, see LICENSE for more details.10"""11from jinja.filters import FILTERS as DEFAULT_FILTERS12from jinja.tests import TESTS as DEFAULT_TESTS13from jinja.utils import debug_context13from jinja.utils import debug_context, safe_range141516DEFAULT_NAMESPACE = {17 'range': range,17 'range': safe_range,18 'debug': debug_context19}
modified:jinja/environment.py+19 added-4 removed
10 unmodified lines
11import re12from jinja.lexer import Lexer13from jinja.parser import Parser14from jinja.loaders import LoaderWrapper15from jinja.datastructure import Undefined, Context, Markup15from jinja.datastructure import Undefined, Context, Markup, FakeTranslator16from jinja.utils import escape17from jinja.exceptions import FilterNotFound, TestNotFound, SecurityException18from jinja.defaults import DEFAULT_FILTERS, DEFAULT_TESTS, DEFAULT_NAMESPACE19
81 unmodified lines
101 return unicode(value)102 except UnicodeError:103 return str(value).decode(self.charset, 'ignore')104105 def get_translator(self, context):106 """107 Return the translator for i18n.108109 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()114115 def apply_filters(self, value, context, filters):116 """117 Apply a list of filters on the variable.118 """
40 unmodified lines
159 raise SecurityException('unsafe attributed %r accessed' % name)160 node = getattr(node, name)161 return node162153 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 lines
171 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)178167 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()190191 def finish_var(self, value):192 """
13 unmodified lines
modified:jinja/utils.py+22 added-3 removed
21 unmodified lines
22 from collections import deque23except ImportError:24 deque = None2526#: number of maximal range items27MAX_RANGE = 10000002829_debug_info_re = re.compile(r'^\s*\# DEBUG\(filename=(.*?), lineno=(.*?)\)$')3031_escape_pairs = {32 '&': '&amp;',
87 unmodified lines
120 yield node.lineno, node.singular, node.plural121 queue.extend(node.getChildNodes())122123121def debug_context():124def 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())130debug_context.jinja_context_callable = True131132133def 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)148149150# python2.4 and lower has a bug regarding joining of broken generators151if sys.hexversion < (2, 5):152 def capture_generator(gen):153 """
210 unmodified lines
modified:www/download.html+1 added-1 removed
24 unmodified lines
25 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 lines
modified:www/index.html+3 added-3 removed
38 unmodified lines
39 <span class="cp">{%</span> <span class="k">endfor</span> <span class="cp">%}</span>40 <span class="nt">&lt;/ul&gt;</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