some documentation updates
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 7b5680c · Browse files · 12 files·+353 added−38 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+353 added−38 removed
- tests:+1 added−1 removed
- other:+352 added−37 removed
Provenance
- Commit
ed98cac- Tree
02dd637- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
7b5680c
12 files changed+353 added−38 removed
modified:docs/_static/style.css+28 added-18 removed
79 unmodified lines80 h1.heading span {81 display: none;82 }83 84-h2.subheading {85- margin: -55px 0 35px 200px;86- font-weight: normal;87- font-size: 30px;88- color: #444;89-}90-91-h2.plain {92- margin: 0;93-}94-84 #jinjalogo {85 background-image: url(jinjalogo.png);86 background-repeat: no-repeat;87 width: 400px;8 unmodified lines96 border-left: 1px solid #eee;97 background: url(watermark_blur.png) -120px -114px;98 }99 100+#contentwrapper h2,101+#contentwrapper h2 a {102+ color: #222;103+ font-size: 24px;104+ margin: 20px 0 0 0;105+}106+107 #contentwrapper h3,108 #contentwrapper h3 a {109 color: #b41717;114- font-size: 26px;115- margin: 20px 0 0 -5px;116-}117-118-#contentwrapper h4,119-#contentwrapper h4 a {120- color: #b41717;110 font-size: 20px;111 margin: 20px 0 0 0;112 }113 198 unmodified lines312 313 dl dt big {314 font-size: 100%;315 }316+317+ul.search {318+ margin: 10px 0 0 30px;319+ padding: 0;320+}321+322+ul.search li {323+ margin: 10px 0 0 0;324+ padding: 0;325+}326+327+ul.search div.context {328+ font-size: 12px;329+ padding: 4px 0 0 20px;330+ color: #888;331+}332+333+span.highlight {334+ background-color: #eee;335+ border: 1px solid #ccc;336+}modified:docs/_templates/layout.html+1 added
39 unmodified lines40414243444546474828 unmodified lines39 unmodified lines {%- endif %} {%- if prev %} <link rel="prev" title="{{ prev.title|striptags }}" href="{{ prev.link|e }}"> {%- endif %} {% block extrahead %}{% endblock %} </head> <body> <div id="content"> <div class="header">28 unmodified linesmodified:docs/_templates/search.html+4 added-4 removed
9 unmodified lines1011121314151617141516171819202114 unmodified lines9 unmodified lines words into the box below and click "search". Note that the search function will automatically search for all of the words. Pages containing less words won't appear in the result list. </p> <form action="" method="get"> <input type="text" name="q" value="" /> <input type="submit" value="search" /> </form> <form action="" method="get"><p> <input type="text" name="q" value=""> <input type="submit" value="search"> </p></form> {% if search_performed %} <h2>Search Results</h2> {% if not search_results %} <p>Your search did not match any results.</p>14 unmodified linesmodified:docs/api.rst+16 added-5 removed
45 unmodified lines46 47 High Level API48 --------------49 50-.. autoclass:: jinja2.environment.Environment51- :members: from_string, get_template, join_path, overlay50+.. autoclass:: jinja2.environment.Environment([options])51+ :members: from_string, get_template, join_path, parse52 53 .. attribute:: shared54 55 If a template was created by using the :class:`Template` constructor26 unmodified lines82 in a template and (if the optimizer is enabled) may not be83 overridden by templates. As long as no template was loaded it's safe84 to modify this dict. For more details see :ref:`global-namespace`.85 86+ .. automethod:: overlay([options])87 88+89 .. autoclass:: jinja2.Template88- :members: render, stream, generate, make_module, module90+ :members: make_module, module, new_context91 92 .. attribute:: globals93 92- foo94+ The dict with the globals of that template. It's unsafe to modify95+ this dict as it may be shared with other templates or the environment96+ that loaded the template.97 98 .. attribute:: name99 96- foo100+ The loading name of the template. If the template was loaded from a101+ string this is `None`.102 103+ .. automethod:: render([context])104 105+ .. automethod:: generate([context])106+107+ .. automethod:: stream([context])108+109+110 .. autoclass:: jinja2.environment.TemplateStream111 :members: disable_buffering, enable_buffering112 113 236 unmodified linesadded:docs/extensions.rst+88 added
1+.. _jinja-extensions:2+3+Extensions4+==========5+6+.. module:: jinja2.ext7+8+Jinja2 supports extensions that can add extra filters, tests, globals or even9+extend the parser. The main motivation of extensions is it to move often used10+code into a reusable class like adding support for internationalization.11+12+13+Adding Extensions14+-----------------15+16+Extensions are added to the Jinja2 environment at creation time. Once the17+environment is created additional extensions cannot be added. To add an18+extension pass a list of extension classes or import paths to the19+`environment` parameter of the :class:`Environment` constructor. The following20+example creates a Jinja2 environment with the i18n extension loaded::21+22+ jinja_env = Environment(extensions=['jinja.ext.i18n'])23+24+25+Built-in Extensions26+-------------------27+28+.. _i18n-extension:29+30+i18n31+~~~~32+33+The i18n extension can be used in combination with `gettext`_ or `babel`_.34+If the i18n extension is enabled Jinja2 provides a `trans` statement that35+marks the wrapped string as translatable and calls `gettext`.36+37+After enabling dummy `_`, `gettext` and `ngettext` functions are added to38+the template globals. A internationalized application has to override those39+methods with more useful versions.40+41+For a web application that is available in multiple languages but gives all42+the users the same language (for example a multilingual forum software43+installed for a French community) may load the translations once and add the44+translation methods to the environment at environment generation time::45+46+ translations = get_gettext_translations()47+ env = Environment(extensions=['jinja.ext.i18n'])48+ env.globals.update(49+ gettext=translations.ugettext,50+ ngettext=translations.ungettext51+ )52+53+The `get_gettext_translations` function would return the translator for the54+current configuration. Keep in mind that Jinja2 uses unicode internally so55+you must pass the `ugettext` and `ungettext` functions to the template.56+57+The default `_` function injected by the extension calls `gettext`58+automatically.59+60+If you want to pass the gettext function into the context at render time61+because you don't know the language/translations earlier and the optimizer62+is enabled (which it is per default), you have to unregister the `gettext`63+and `ugettext` functions first::64+65+ del env.globals['gettext'], env.globals['ugettext']66+67+Jinja2 also provides a way to extract recognized strings. For one the68+`jinja.ext` module provides a function that can return all the occurences69+of gettext calls in a node (as returned by :meth:`Environment.parse`):70+71+.. autofunction:: extract_from_ast72+73+If `babel`_ is installed :ref:`the babel integration <babel-integration>`74+can be used to.75+76+The usage of the `i18n` extension for template designers is covered as part77+:ref:`of the template documentation <i18n-in-templates>`.78+79+80+.. _gettext: http://docs.python.org/dev/library/gettext81+.. _babel: http://babel.edgewall.org/82+83+.. _writing-extensions:84+85+Writing Extensions86+------------------87+88+TODOmodified:docs/index.rst+6 added
9 unmodified lines10 11 intro12 api13 templates14+ extensions15+ integration16 17 changelog18 19+If you can't find the information you're looking for, have a look at the20+index of try to find it using the search function:21+22 * :ref:`genindex`23+* :ref:`search`added:docs/integration.rst+68 added
1+Integration2+===========3+4+Jinja2 provides some code for integration into other tools such as frameworks,5+the `Babel`_ library or your favourite editor for fancy code highlighting.6+This is a brief description of whats included.7+8+.. _babel-integration:9+10+Babel Integration11+-----------------12+13+Jinja provides support for extracting gettext messages from templates via a14+`Babel`_ extractor entry point called `jinja2.ext.babel_extract`. The Babel15+support is implemented as part of the :ref:`i18n-extension` extension.16+17+Gettext messages extracted from both `trans` tags and code expressions.18+19+To extract gettext messages from templates, the project needs a Jinja2 section20+in its Babel extraction method `mapping file`_:21+22+.. sourcecode:: ini23+24+ [jinja: **/templates/**.html]25+ encoding = utf-826+27+The syntax related options of the :class:`Environment` are also available as28+configuration values in the mapping file. For example to tell the extraction29+that templates use ``%`` as `line_statement_prefix` you can use this code:30+31+.. sourcecode:: ini32+33+ [jinja: **/templates/**.html]34+ encoding = utf-835+ line_statement_prefix = %36+37+:ref:`jinja-extensions` may also be defined by passing a comma separated list38+of import paths as `extensions` value. The i18n extension is added39+automatically.40+41+.. _mapping file: http://babel.edgewall.org/wiki/Documentation/messages.html#extraction-method-mapping-and-configuration42+43+Django44+------45+46+TODO47+48+Pylons49+------50+51+TODO52+53+WSGI54+----55+56+TODO57+58+TextMate59+--------60+61+TODO62+63+Vim64+---65+66+TODO67+68+.. _Babel: http://babel.edgewall.org/modified:docs/intro.rst+55 added-3 removed
11 unmodified lines12 13 The key-features are...14 15 - ... **configurable syntax**. If you are generating LaTeX or other formats16- with Jinja you can change the delimiters to something that integrates better16+ with Jinja2 you can change the delimiters to something that integrates better17 into the LaTeX markup.18 19 - ... **fast**. While performance is not the primarily target of Jinja2 it's20 surprisingly fast. The overhead compared to regular Python code was reduced21 to the very minimum.22 23 - ... **easy to debug**. Jinja2 integrates directly into the python traceback24- system which allows you to debug Jinja templates with regular python24+ system which allows you to debug Jinja2 templates with regular python25 debugging helpers.26 27 - ... **secure**. It's possible to evaluate untrusted template code if the28 optional sandbox is enabled. This allows Jinja2 to be used as templating9 unmodified lines38 39 .. _ctypes: http://python.net/crew/theller/ctypes/40 41 42+Installation43+------------44+45+You have multiple ways to install Jinja2. If you are unsure what to do, go46+with the Python egg or tarball.47+48+As a Python egg (via easy_install)49+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~50+51+You can install the most recent Jinja2 version using `easy_install`_::52+53+ sudo easy_install Jinja254+55+This will install a Jinja2 egg in your Python installation's site-packages56+directory.57+58+From the tarball release59+~~~~~~~~~~~~~~~~~~~~~~~~~60+61+1. Download the most recent tarball from the `download page`_62+2. Unpack the tarball63+3. ``sudo python setup.py install``64+65+Note that the last command will automatically download and install66+`setuptools`_ if you don't already have it installed. This requires a working67+internet connection.68+69+This will install Jinja2 into your Python installation's site-packages directory.70+71+Installing the development version72+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~73+74+1. Install `mercurial`_75+2. ``svn co http://dev.pocoo.org/hg/jinja2-main jinja2``76+3. ``cd jinja2``77+4. ``ln -s jinja2 /usr/lib/python2.X/site-packages``78+79+As an alternative to steps 4 you can also do ``python setup.py develop``80+which will install the package via setuptools in development mode. This also81+has the advantage that the C extensions are compiled.82+83+Alternative you can use `easy_install`_ to install the current development84+snapshot::85+86+ sudo easy_install Jinja2==dev87+88+.. _download page: http://jinja.pocoo.org/2/download89+.. _setuptools: http://peak.telecommunity.com/DevCenter/setuptools90+.. _easy_install: http://peak.telecommunity.com/DevCenter/EasyInstall91+.. _mercurial: http://www.selenic.com/mercurial/92+93+94 Basic API Usage95 ---------------96 45-This section gives you a brief introduction to the Python API for Jinja templates.97+This section gives you a brief introduction to the Python API for Jinja2 templates.98 99 The most basic way to create a template and render it is through100 :class:`Template`. This however is not the recommended way to work with it,101 but the easiest11 unmodified linesmodified:docs/templates.rst+71 added-1 removed
926 unmodified lines927 with HTML are generated each paragraph between 20 and 100 words. If html928 is disabled regular text is returned. This is useful to generate simple929 contents for layout testing.930 931-.. function:: dict(**items)931+.. function:: dict(\**items)932 933 A convenient alternative to dict literals. ``{'foo': 'bar'}`` is the same934 as ``dict(foo='bar')``.935+936+937+Extensions938+----------939+940+The following sections cover the built-in Jinja2 extensions that may be941+enabled by the application. The application could also provide further942+extensions not covered by this documentation. In that case there should943+be a separate document explaining the extensions.944+945+.. _i18n-in-templates:946+947+i18n948+~~~~949+950+If the i18n extension is enabled it's possible to mark parts in the template951+as translatable. To mark a section as translatable you can use `trans`::952+953+ <p>{% trans %}Hello {{ user }}!{% endtrans %}</p>954+955+To translate a template expression --- say, using template filters or just956+accessing an attribute of an object --- you need to bind the expression to a957+name for use within the translation block::958+959+ <p>{% trans user=user.username %}Hello {{ user }}!{% endtrans %}</p>960+961+If you need to bind more than one expression inside a `trans` tag, separate962+the pieces with a comma (``,``)::963+964+ {% trans book_title=book.title, author=author.name %}965+ This is {{ book_title }} by {{ author }}966+ {% endtrans %}967+968+Inside trans tags no statements are allowed, only variable tags are.969+970+To pluralize, specify both the singular and plural forms with the `pluralize`971+tag, which appears between `trans` and `endtrans`::972+973+ {% trans count=list|length %}974+ There is {{ count }} {{ name }} object.975+ {% pluralize %}976+ There are {{ count }} {{ name }} objects.977+ {% endtrans %}978+979+Per default the first variable in a block is used to determine the correct980+singular or plural form. If that doesn't work out you can specify the name981+which should be used for pluralizing by adding it as parameter to `pluralize`::982+983+ {% trans ..., user_count=users|length %}...984+ {% pluralize user_count %}...{% endtrans %}985+986+It's also possible to translate strings in expressions. For that purpose987+three functions exist:988+989+_ `gettext`: translate a single string990+- `ngettext`: translate a pluralizable string991+- `_`: alias for `gettext`992+993+For example you can print a translated string easily this way::994+995+ {{ _('Hello World!') }}996+997+To use placeholders you can use the `format` filter::998+999+ {{ _('Hello %(user)s!')|format(user=user.username) }}1000+ or1001+ {{ _('Hello %s')|format(user.username) }}1002+1003+For multiple placeholders always use keyword arguments to `format` as other1004+languages may not use the words in the same order.modified:jinja2/environment.py+5 added-1 removed
110 unmodified lines111 removed (block, not variable tag!). Defaults to `False`.112 113 `extensions`114 List of Jinja extensions to use. This can either be import paths115- as strings or extension classes.115+ as strings or extension classes. For more information have a116+ look at :ref:`the extensions documentation <jinja-extensions>`.117 118 `optimized`119 should the optimizer be enabled? Default is `True`.120 161 unmodified lines282 """Parse the sourcecode and return the abstract syntax tree. This283 tree of nodes is used by the compiler to convert the template into284 executable source- or bytecode. This is useful for debugging or to285 extract information from templates.286+287+ If you are :ref:`developing Jinja2 extensions <writing-extensions>`288+ this gives you a good overview of the node tree generated.289 """290 try:291 return Parser(self, source, filename).parse()292 except TemplateSyntaxError, e:387 unmodified linesmodified:jinja2/ext.py+10 added-5 removed
13 unmodified lines14 from jinja2 import nodes15 from jinja2.environment import get_spontaneous_environment16 from jinja2.runtime import Undefined, concat17 from jinja2.exceptions import TemplateAssertionError, TemplateSyntaxError18-from jinja2.utils import import_string, Markup18+from jinja2.utils import contextfunction, import_string, Markup19 20 21 # the only real useful gettext functions for a Jinja template. Note22 # that ugettext must be assigned to gettext as Jinja doesn't support50 unmodified lines73 [], [], body74 )75 76 77-class TransExtension(Extension):77+class InternationalizationExtension(Extension):78 """This extension adds gettext support to Jinja."""79 tags = set(['trans'])80 81 def __init__(self, environment):82 Extension.__init__(self, environment)83 environment.globals.update({84- '_': lambda x: x,84+ '_': contextfunction(lambda c, x: c['gettext'](x)),85 'gettext': lambda x: x,86 'ngettext': lambda s, p, n: (s, p)[n != 1]87 })88 194 unmodified lines283 extension = extension.strip()284 if not extension:285 continue286 extension = import_string(extension)287- if extension is TransExtension:287+ if extension is InternationalizationExtension:288 have_trans_extension = True289 extensions.append(extension)290 if not have_trans_extension:291- extensions.append(TransExtension)291+ extensions.append(InternationalizationExtension)292 293 environment = get_spontaneous_environment(294 options.get('block_start_string', '{%'),295 options.get('block_end_string', '%}'),13 unmodified lines309 310 node = environment.parse(fileobj.read().decode(encoding))311 for lineno, func, message in extract_from_ast(node, keywords):312 yield lineno, func, message, []313+314+315+#: nicer import names316+i18n = InternationalizationExtension317+cache = CacheExtensionmodified:tests/test_i18n.py+1 added-1 removed
44 unmodified lines45 46 47 i18n_env = Environment(48 loader=DictLoader(templates),49- extensions=['jinja2.ext.TransExtension']49+ extensions=['jinja2.ext.i18n']50 )51 i18n_env.globals.update({52 '_': gettext,53 'gettext': gettext,33 unmodified lines