devintro.txt
This file
Path
docs/src/devintro.txt
190 lines · 6.5 KiB
Last changed by
[svn] some minor updates in jinjaArmin Ronacherbefore adoption649c7b9
History of this fileTake it
1====================2Developer Quickstart3====================45This part of the documentation shows you how to embed 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.2627Basically the important method on a template is the `render` method. It28takes either a dict or keyword arguments. All keyword arguments appear29in the template as variables.3031So these two snippets do the same:3233.. sourcecode:: python3435 tmpl.render(36 knights='we say nih',37 spam='and eggs'38 )3940.. sourcecode:: python4142 tmpl.render({43 'knights': 'we say nih',44 'spam': 'and eggs'45 })4647The Environment48===============4950[[environment_doc]]5152The environment provides the following useful functions and properties in53addition to the initialization values:5455=========================== ==================================================56``parse(source, filename)`` Parse the sourcecode and return the abstract57 syntax tree. This tree of nodes is used by the58 `translators`_ to convert the template into59 executable source- or bytecode.60``lex(source, filename)`` Tokenize the given sourcecode and return a61 generator of tuples in the form62 ``(lineno, token, value)``. The filename is just63 used in the exceptions raised.64 **New in Jinja 1.1**65``from_string(source)`` Load and parse a template source and translate it66 into eval-able Python code. This code is wrapped67 within a `Template` class that allows you to68 render it.69``get_template(name)`` Load a template from a loader. If the template70 does not exist, you will get a `TemplateNotFound`71 exception.72=========================== ==================================================7374There are also some internal functions on the environment used by the template75evaluation code to keep it sandboxed.7677Undefined Values78================7980If a template designer tries to access a not defined value the return value81will be the `undefined_singleton` specified in the environment. The default82one is the `SilentUndefined` which fails in no case. Additionally there is83a special undefined type called the `ComplainingUndefined` which is located84in the `jinja.datastructure` module. It will raise exceptions when compared85with other types, or when rendered.8687Theoretically you can provide your own singleton by subclassing88`AbstractUndefindedType` and creating an instance of it using `make_undefined`89(both located in `jinja.datastructure`) but those two types should cover90the basic use cases. The `Undefined` object in that module exists for91backwards compatibility and is an alias for `SilentUndefined`.9293To create your own undefined singleton do something like this:9495.. sourcecode:: jinja9697 from jinja.datastructure import AbstractUndefinedType, make_undefined9899 class MyUndefinedType(AbstractUndefindedType):100 __slots__ = ()101102 def __iter__(self):103 return iter(int, 0)104105 def __reduce__(self):106 return 'MyUndefined'107108 MyUndefined = make_undefined(MyUndefinedType)109110The only thing you have to do is to override `__reduce__` so that it returns111the name of the singleton instance and create the instance using112`make_undefined`. Everything else is up to you. Note that currently attributes113on undefined objects are available in the Jinja layer too which however114will change in one of the next Jinja versions. So if you put a `foo` attribute115on your undefined singleton you will be able to do ``{{ undefined.foo }}``116by now but certainly not in the future.117118This limitation currently exists because undefined is treated as normal object119and thus affected by normal getattr calls.120121122Automatic Escaping123==================124125Jinja provides a way for automatic escaping, but we do not recommend using it.126Because Jinja was designed as multi purpose template engine there are some127issues with automatic escaping. For example filters don't deal with markup128data. Also you can easily bypass the automatic escaping so it's not something129you can expect to "just work". Also there is a huge overhead when escaping130everything.131132The best idea is to think about which data already contains html, which will133probably contain (eg: every user input, etc) etc. And live with self escaping.134135That's usually a much better idea.136137138Loading Templates From Files139============================140141Loading templates from a string is always a bad idea. It doesn't allow template142inheritance and is also slow since it parses and compiles the template again143and again whereas loaders can cache the template code.144145All you have to do is to define a loader and use the `get_template` function.146147.. sourcecode:: python148149 from jinja import Environment, FileSystemLoader150 env = Environment(loader=FileSystemLoader('templates'))151 tmpl = env.get_template('index.html')152 print tmpl.render(name='John Doe')153154This tells jinja to look for templates in the ``templates`` folder. It's a155better idea to use an absolute path here though. For a list of supported156loaders or how to write your own, head over to the `loader`_ documentation.157158Adding Filters159==============160161If you want to add additional filters to the environment, the best way is to162modify the ``filters`` attribute and not to pass a dict to the environment.163If you pass it a dict it will not include the default filters!164165.. sourcecode:: python166167 from mylib import my_cool_filter168 env.filters['mycoolfilter'] = my_cool_filter169170Writing filter functions is explained in the `filter development`_ section.171172Adding Tests173============174175Adding additional tests works analogous to filters:176177.. sourcecode:: python178179 from mylib import my_cool_test180 env.tests['mycooltest'] = my_cool_test181182Writing tests is explained in the `test development`_ section.183184185.. _installation: installation.txt186.. _context documentation: contextenv.txt187.. _loader: loaders.txt188.. _translators: translators.txt189.. _filter development: filters.txt190.. _test development: tests.txt