Skip to content
Myr

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

12 files+353 added−38 removed

modified:docs/_static/style.css+28 added-18 removed
79 unmodified lines
80h1.heading span {81 display: none;82}8384h2.subheading {85 margin: -55px 0 35px 200px;86 font-weight: normal;87 font-size: 30px;88 color: #444;89}9091h2.plain {92 margin: 0;93}9484#jinjalogo {85 background-image: url(jinjalogo.png);86 background-repeat: no-repeat;87 width: 400px;
8 unmodified lines
96 border-left: 1px solid #eee;97 background: url(watermark_blur.png) -120px -114px;98}99100#contentwrapper h2,101#contentwrapper h2 a {102 color: #222;103 font-size: 24px;104 margin: 20px 0 0 0;105}106107#contentwrapper h3,108#contentwrapper h3 a {109 color: #b41717;114 font-size: 26px;115 margin: 20px 0 0 -5px;116}117118#contentwrapper h4,119#contentwrapper h4 a {120 color: #b41717;110 font-size: 20px;111 margin: 20px 0 0 0;112}113
198 unmodified lines
312313dl dt big {314 font-size: 100%;315}316317ul.search {318 margin: 10px 0 0 30px;319 padding: 0;320}321322ul.search li {323 margin: 10px 0 0 0;324 padding: 0;325}326327ul.search div.context {328 font-size: 12px;329 padding: 4px 0 0 20px;330 color: #888;331}332333span.highlight {334 background-color: #eee;335 border: 1px solid #ccc;336}
modified:docs/_templates/layout.html+1 added
modified:docs/_templates/search.html+4 added-4 removed
modified:docs/api.rst+16 added-5 removed
45 unmodified lines
4647High Level API48--------------4950.. 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, parse5253 .. attribute:: shared5455 If a template was created by using the :class:`Template` constructor
26 unmodified lines
82 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`.8586 .. automethod:: overlay([options])878889.. autoclass:: jinja2.Template88 :members: render, stream, generate, make_module, module90 :members: make_module, module, new_context9192 .. attribute:: globals9392 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.9798 .. attribute:: name9996 foo100 The loading name of the template. If the template was loaded from a101 string this is `None`.102103 .. automethod:: render([context])104105 .. automethod:: generate([context])106107 .. automethod:: stream([context])108109110.. autoclass:: jinja2.environment.TemplateStream111 :members: disable_buffering, enable_buffering112113
236 unmodified lines
added:docs/extensions.rst+88 added
1.. _jinja-extensions:23Extensions4==========56.. module:: jinja2.ext78Jinja2 supports extensions that can add extra filters, tests, globals or even9extend the parser. The main motivation of extensions is it to move often used10code into a reusable class like adding support for internationalization.111213Adding Extensions14-----------------1516Extensions are added to the Jinja2 environment at creation time. Once the17environment is created additional extensions cannot be added. To add an18extension pass a list of extension classes or import paths to the19`environment` parameter of the :class:`Environment` constructor. The following20example creates a Jinja2 environment with the i18n extension loaded::2122 jinja_env = Environment(extensions=['jinja.ext.i18n'])232425Built-in Extensions26-------------------2728.. _i18n-extension:2930i18n31~~~~3233The i18n extension can be used in combination with `gettext`_ or `babel`_.34If the i18n extension is enabled Jinja2 provides a `trans` statement that35marks the wrapped string as translatable and calls `gettext`.3637After enabling dummy `_`, `gettext` and `ngettext` functions are added to38the template globals. A internationalized application has to override those39methods with more useful versions.4041For a web application that is available in multiple languages but gives all42the users the same language (for example a multilingual forum software43installed for a French community) may load the translations once and add the44translation methods to the environment at environment generation time::4546 translations = get_gettext_translations()47 env = Environment(extensions=['jinja.ext.i18n'])48 env.globals.update(49 gettext=translations.ugettext,50 ngettext=translations.ungettext51 )5253The `get_gettext_translations` function would return the translator for the54current configuration. Keep in mind that Jinja2 uses unicode internally so55you must pass the `ugettext` and `ungettext` functions to the template.5657The default `_` function injected by the extension calls `gettext`58automatically.5960If you want to pass the gettext function into the context at render time61because you don't know the language/translations earlier and the optimizer62is enabled (which it is per default), you have to unregister the `gettext`63and `ugettext` functions first::6465 del env.globals['gettext'], env.globals['ugettext']6667Jinja2 also provides a way to extract recognized strings. For one the68`jinja.ext` module provides a function that can return all the occurences69of gettext calls in a node (as returned by :meth:`Environment.parse`):7071.. autofunction:: extract_from_ast7273If `babel`_ is installed :ref:`the babel integration <babel-integration>`74can be used to.7576The usage of the `i18n` extension for template designers is covered as part77:ref:`of the template documentation <i18n-in-templates>`.787980.. _gettext: http://docs.python.org/dev/library/gettext81.. _babel: http://babel.edgewall.org/8283.. _writing-extensions:8485Writing Extensions86------------------8788TODO
modified:docs/index.rst+6 added
9 unmodified lines
1011 intro12 api13 templates14 extensions15 integration1617 changelog1819If you can't find the information you're looking for, have a look at the20index of try to find it using the search function:2122* :ref:`genindex`23* :ref:`search`
added:docs/integration.rst+68 added
1Integration2===========34Jinja2 provides some code for integration into other tools such as frameworks,5the `Babel`_ library or your favourite editor for fancy code highlighting.6This is a brief description of whats included.78.. _babel-integration:910Babel Integration11-----------------1213Jinja provides support for extracting gettext messages from templates via a14`Babel`_ extractor entry point called `jinja2.ext.babel_extract`. The Babel15support is implemented as part of the :ref:`i18n-extension` extension.1617Gettext messages extracted from both `trans` tags and code expressions.1819To extract gettext messages from templates, the project needs a Jinja2 section20in its Babel extraction method `mapping file`_:2122.. sourcecode:: ini2324 [jinja: **/templates/**.html]25 encoding = utf-82627The syntax related options of the :class:`Environment` are also available as28configuration values in the mapping file. For example to tell the extraction29that templates use ``%`` as `line_statement_prefix` you can use this code:3031.. sourcecode:: ini3233 [jinja: **/templates/**.html]34 encoding = utf-835 line_statement_prefix = %3637:ref:`jinja-extensions` may also be defined by passing a comma separated list38of import paths as `extensions` value. The i18n extension is added39automatically.4041.. _mapping file: http://babel.edgewall.org/wiki/Documentation/messages.html#extraction-method-mapping-and-configuration4243Django44------4546TODO4748Pylons49------5051TODO5253WSGI54----5556TODO5758TextMate59--------6061TODO6263Vim64---6566TODO6768.. _Babel: http://babel.edgewall.org/
modified:docs/intro.rst+55 added-3 removed
11 unmodified lines
1213The key-features are...1415- ... **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.1819- ... **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.2223- ... **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.2627- ... **secure**. It's possible to evaluate untrusted template code if the28 optional sandbox is enabled. This allows Jinja2 to be used as templating
9 unmodified lines
3839.. _ctypes: http://python.net/crew/theller/ctypes/404142Installation43------------4445You have multiple ways to install Jinja2. If you are unsure what to do, go46with the Python egg or tarball.4748As a Python egg (via easy_install)49~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~5051You can install the most recent Jinja2 version using `easy_install`_::5253 sudo easy_install Jinja25455This will install a Jinja2 egg in your Python installation's site-packages56directory.5758From the tarball release59~~~~~~~~~~~~~~~~~~~~~~~~~60611. Download the most recent tarball from the `download page`_622. Unpack the tarball633. ``sudo python setup.py install``6465Note that the last command will automatically download and install66`setuptools`_ if you don't already have it installed. This requires a working67internet connection.6869This will install Jinja2 into your Python installation's site-packages directory.7071Installing the development version72~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~73741. Install `mercurial`_752. ``svn co http://dev.pocoo.org/hg/jinja2-main jinja2``763. ``cd jinja2``774. ``ln -s jinja2 /usr/lib/python2.X/site-packages``7879As an alternative to steps 4 you can also do ``python setup.py develop``80which will install the package via setuptools in development mode. This also81has the advantage that the C extensions are compiled.8283Alternative you can use `easy_install`_ to install the current development84snapshot::8586 sudo easy_install Jinja2==dev8788.. _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/929394Basic API Usage95---------------9645This section gives you a brief introduction to the Python API for Jinja templates.97This section gives you a brief introduction to the Python API for Jinja2 templates.9899The 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,101but the easiest
11 unmodified lines
modified:docs/templates.rst+71 added-1 removed
926 unmodified lines
927 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.930931.. function:: dict(**items)931.. function:: dict(\**items)932933 A convenient alternative to dict literals. ``{'foo': 'bar'}`` is the same934 as ``dict(foo='bar')``.935936937Extensions938----------939940The following sections cover the built-in Jinja2 extensions that may be941enabled by the application. The application could also provide further942extensions not covered by this documentation. In that case there should943be a separate document explaining the extensions.944945.. _i18n-in-templates:946947i18n948~~~~949950If the i18n extension is enabled it's possible to mark parts in the template951as translatable. To mark a section as translatable you can use `trans`::952953 <p>{% trans %}Hello {{ user }}!{% endtrans %}</p>954955To translate a template expression --- say, using template filters or just956accessing an attribute of an object --- you need to bind the expression to a957name for use within the translation block::958959 <p>{% trans user=user.username %}Hello {{ user }}!{% endtrans %}</p>960961If you need to bind more than one expression inside a `trans` tag, separate962the pieces with a comma (``,``)::963964 {% trans book_title=book.title, author=author.name %}965 This is {{ book_title }} by {{ author }}966 {% endtrans %}967968Inside trans tags no statements are allowed, only variable tags are.969970To pluralize, specify both the singular and plural forms with the `pluralize`971tag, which appears between `trans` and `endtrans`::972973 {% trans count=list|length %}974 There is {{ count }} {{ name }} object.975 {% pluralize %}976 There are {{ count }} {{ name }} objects.977 {% endtrans %}978979Per default the first variable in a block is used to determine the correct980singular or plural form. If that doesn't work out you can specify the name981which should be used for pluralizing by adding it as parameter to `pluralize`::982983 {% trans ..., user_count=users|length %}...984 {% pluralize user_count %}...{% endtrans %}985986It's also possible to translate strings in expressions. For that purpose987three functions exist:988989_ `gettext`: translate a single string990- `ngettext`: translate a pluralizable string991- `_`: alias for `gettext`992993For example you can print a translated string easily this way::994995 {{ _('Hello World!') }}996997To use placeholders you can use the `format` filter::998999 {{ _('Hello %(user)s!')|format(user=user.username) }}1000 or1001 {{ _('Hello %s')|format(user.username) }}10021003For multiple placeholders always use keyword arguments to `format` as other1004languages may not use the words in the same order.
modified:jinja2/environment.py+5 added-1 removed
110 unmodified lines
111 removed (block, not variable tag!). Defaults to `False`.112113 `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>`.117118 `optimized`119 should the optimizer be enabled? Default is `True`.120
161 unmodified lines
282 """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.286287 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 lines
modified:jinja2/ext.py+10 added-5 removed
13 unmodified lines
14from jinja2 import nodes15from jinja2.environment import get_spontaneous_environment16from jinja2.runtime import Undefined, concat17from jinja2.exceptions import TemplateAssertionError, TemplateSyntaxError18from jinja2.utils import import_string, Markup18from jinja2.utils import contextfunction, import_string, Markup192021# the only real useful gettext functions for a Jinja template. Note22# that ugettext must be assigned to gettext as Jinja doesn't support
50 unmodified lines
73 [], [], body74 )757677class TransExtension(Extension):77class InternationalizationExtension(Extension):78 """This extension adds gettext support to Jinja."""79 tags = set(['trans'])8081 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 lines
283 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)292293 environment = get_spontaneous_environment(294 options.get('block_start_string', '{%'),295 options.get('block_end_string', '%}'),
13 unmodified lines
309310 node = environment.parse(fileobj.read().decode(encoding))311 for lineno, func, message in extract_from_ast(node, keywords):312 yield lineno, func, message, []313314315#: nicer import names316i18n = InternationalizationExtension317cache = CacheExtension
modified:tests/test_i18n.py+1 added-1 removed
44 unmodified lines
454647i18n_env = Environment(48 loader=DictLoader(templates),49 extensions=['jinja2.ext.TransExtension']49 extensions=['jinja2.ext.i18n']50)51i18n_env.globals.update({52 '_': gettext,53 'gettext': gettext,
33 unmodified lines