Skip to content
Myr

devintro.txt

This file

Path

docs/src/devintro.txt

139 lines · 5.5 KiB

Last changed by

[svn] add first part of jinja documentationArmin Ronacherbefore adoption37a8851

History of this file

Take it

1====================2Developer Quickstart3====================45This part of the documentation shows you how to embedd Jinja into your6application.78Starting Up9===========1011Here the quickest way to create a template from a string and render it:1213.. sourcecode:: python1415    from jinja import Environment16    env = Environment()17    tmpl = env.from_string('Hello {{ name }}!')18    print tmpl.render(name='John Doe')1920This example should output the following string after execution::2122    Hello John Doe!2324If you receive an error check if you have a typo in your code. If not have25a look at the `installation`_ page for troubleshooting.2627The Environment28===============2930The core component of Jinja is the `Environment`. It helds important shared31variables like configuration, filters, tests, globals and other stuff.3233Here the possible initialisation parameters:3435=========================== ==================================================36``block_start_string`` *    the string marking the begin of a block. this37                            defaults to ``'{%'``.38``block_end_string`` *      the string marking the end of a block. defaults39                            to ``'%}'``.40``variable_start_string`` * the string marking the begin of a print41                            statement. defaults to ``'{{'``.42``comment_start_string`` *  the string marking the begin of a43                            comment. defaults to ``'{#'``.44``comment_end_string`` *    the string marking the end of a comment.45                            defaults to ``'#}'``.46``trim_blocks`` *           If this is set to ``True`` the first newline47                            after a block is removed (block, not48                            variable tag!). Defaults to ``False``.49``auto_escape``             If this is set to ``True`` Jinja will50                            automatically escape all variables using xml51                            escaping methods. If you don't want to escape a52                            string you have to wrap it in a ``Markup``53                            object from the ``jinja.datastructure`` module.54``template_charset``        The charset of the templates. Defaults55                            to ``'utf-8'``.56``charset``                 Charset of all string input data. Defaults57                            to ``'utf-8'``.58``namespace``               Global namespace for all templates.59``loader``                  Specify a template loader.60``filters``                 dict of filters or the default filters if not61                            defined.62``tests``                   dict of tests of the default tests if not defined.63=========================== ==================================================6465All of this variables except those marked with a star(*) are modifyable after66environment initialisation.6768The environment provides the following useful functions and properties69additional to the initialisation values:7071=========================== ==================================================72``parse(source, filename)`` Parse the sourcecode and return the abstract73                            syntax tree. This tree of nodes is used by the74                            `translators`_ to convert the template into75                            executable source- or bytecode.76``from_string(source)``     Load and parse a template source and translate it77                            into evaluable python code. This code is wrapped78                            with in a `Template` class that allows you to79                            render it.80``get_template(name)``      load a template from a loader. If the template81                            does not exist you will get a `TemplateNotFound`82                            exception.83=========================== ==================================================8485There are also some internal functions on the environment used by the template86evaluation code to keep it sandboxed.8788Loading Templates From Files89============================9091Loading templates from a string is always a bad idea. It doesn't allow template92inheritance and is also slow since it parses and compiles the template again93and again whereas loaders can cache the template code.9495All you have to do is to define a loader and use the `get_template` function.9697.. sourcecode:: python9899    from jinja import Environment, FileSystemLoader100    env = Environment(loader=FileSystemLoader('templates'))101    tmpl = env.get_template('index.html')102    print tmpl.render(name='John Doe')103104This tells jinja to look for templates in the ``templates`` folder. It's a105better idea to use an absolute path here though. For a list of supported106loaders or how to write your own, head over to the `loader`_ documentation.107108Adding Filters109==============110111If you want to add additional filters to the environment the best way is to112modify the ``filters`` attribute and not to pass a dict to the environment.113If you pass it a dict it will not include the default filters!114115.. sourcecode:: python116117    from mylib import my_cool_filter118    env.filters['mycoolfilter'] = my_cool_filter119120Writing filter functions is explained in the `filter development`_ section.121122Adding Tests123============124125Adding additional tests works analog to filters:126127.. sourcecode:: python128129    from mylib import my_cool_test130    env.tests['mycooltest'] = my_cool_test131132Writing tests is explained in the `test development`_ section.133134135.. _installation: installation.txt136.. _translators: translators.txt137.. _loader: loaders.txt138.. _filter development: filters.txt139.. _test development: tests.txt