Skip to content
Myr

all calls are proxied by context.call now so that we can inject environment and context as first arguments. This slows calls down a bit but is a lot more user friendly. Added first draft of FAQ

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 9f258ff · Browse files · 10 files+180 added−48 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+180 added−48 removed

  • tests:+7 added−5 removed
  • other:+173 added−43 removed

10 files+180 added−48 removed

added:docs/faq.rst+123 added
1Frequently Asked Questions2==========================34This page answers some of the often asked questions about Jinja.56.. highlight:: html+jinja789Why is it called Jinja?10-----------------------1112The name Jinja was chosen because it's the name of a Japanese temple and13temple and template share a similar pronunciation. It is not named after14the capital city of Uganda.1516How fast is it?17---------------1819We really hate benchmarks especially since they don't reflect much. The20performance of a template depends on many factors and you would have to21benchmark different engines in different situations. The benchmarks from the22testsuite show that Jinja2 has a similar performance to `Mako`_ and is more23than 20 times faster than Django's template engine or Genshi. These numbers24should be taken with tons of salt!2526.. _Mako: http://www.makotemplates.org/2728How Compatible is Jinja2 with Django?29-------------------------------------3031The default syntax of Jinja2 matches Django syntax in many ways. However32this similarity doesn't mean that you can use a Django template unmodified33in Jinja2. For example filter arguments use a function call syntax rather34than a colon to separate filter name and arguments. Additionally the35extension interface in Jinja is fundamentally different from the Django one36which means that your custom tags won't work any longer.3738Generally speaking you will use much less custom extensions as the Jinja39template system allows you to use a certain subset of Python expressions40which can replace most Django extensions. For example instead of using41something like this::4243 {% load comments %}44 {% get_latest_comments 10 as latest_comments %}45 {% for comment in latest_comments %}46 ...47 {% endfor %}4849You will most likely provide an object with attributes to retrieve50comments from the database::5152 {% for comment in models.comments.latest(10) %}53 ...54 {% endfor %}5556Or directly provide the model for quick testing::5758 {% for comment in Comment.objects.order_by('-pub_date')[:10] %}59 ...60 {% endfor %}6162Please keep in mind that even though you may put such things into templates63it still isn't a good idea. Queries should go into the view code and now64the template!6566Isn't it a terrible idea to put Logic into Templates?67-----------------------------------------------------6869Without a doubt you should try to remove as much logic from templates as70possible. But templates without any logic mean that you have to do all71the processing in the code which is boring and stupid. A template engine72that does that is shipped with Python and called `string.Template`. Comes73without loops and if conditions and is by far the fastest template engine74you can get for Python.7576So some amount of logic is required in templates to keep everyone happy.77And Jinja leaves it pretty much to you how much logic you want to put into78templates. There are some restrictions in what you can do and what not.7980Jinja2 neither allows you to put arbitrary Python code into templates nor81does it allow all Python expressions. The operators are limited to the82most common ones and more advanced expressions such as list comprehensions83and generator expressions are not supported. This keeps the template engine84easier to maintain and templates more readable.8586Why is Autoescaping not the Default?87------------------------------------8889There are multiple reasons why automatic escaping is not the default mode90and also not the recommended one. While automatic escaping of variables91means that you will less likely have an XSS problem it also causes a huge92amount of extra processing in the template engine which can cause serious93performance problems. As Python doesn't provide a way to mark strings as94unsafe Jinja has to hack around that limitation by providing a custom95string class (the :class:`Markup` string) that safely interacts with safe96and unsafe strings.9798With explicit escaping however the template engine doesn't have to perform99any safety checks on variables. Also a human knows not to escape integers100or strings that may never contain characters one has to escape or already101HTML markup. For example when iterating over a list over a table of102integers and floats for a table of statistics the template designer can103omit the escaping because he knows that integers or floats don't contain104any unsafe parameters.105106Additionally Jinja2 is a general purpose template engine and not only used107for HTML/XML generation. For example you may generate LaTeX, emails,108CSS, JavaScript, or configuration files.109110Why is the Context immutable?111-----------------------------112113When writing a :func:`contextfunction` or something similar you may have114noticed that the context tries to stop you from modifying it. If you have115managed to modify the context by using an internal context API you may116have noticed that changes in the context don't seem to be visible in the117template. The reason for this is that Jinja uses the context only as118primary data source for template variables for performance reasons.119120If you want to modify the context write a function that returns a variable121instead that one can assign to a variable by using set::122123 {% set comments = get_latest_comments() %}
modified:docs/index.rst+1 added
15 unmodified lines
16 integration17 switching18 tricks1920 faq21 changelog2223If you can't find the information you're looking for, have a look at the24index of try to find it using the search function:
3 unmodified lines
modified:docs/templates.rst+15 added
324 unmodified lines
325 {{ super() }}326 {% endblock %}327328329Named Block End-Tags330~~~~~~~~~~~~~~~~~~~~331332Jinja2 allows you to put the name of the block after the end tag for better333readability::334335 {% block sidebar %}336 {% block inner_sidebar %}337 ...338 {% endblock inner_sidebar %}339 {% endblock sidebar %}340341However the name after the `endblock` word must match the block name.342343344HTML Escaping345-------------346347When generating HTML from templates, there's always a risk that a variable will
717 unmodified lines
modified:jinja2/compiler.py+13 added-24 removed
436 unmodified lines
437 if node is not None and node.lineno != self._last_line:438 self._write_debug_info = node.lineno439 self._last_line = node.lineno440441 def signature(self, node, frame, have_comma=True, extra_kwargs=None):441 def signature(self, node, frame, extra_kwargs=None):442 """Writes a function call to the stream for the current node.443 Per default it will write a leading comma but this can be444 disabled by setting have_comma to False. The extra keyword443 A leading comma is added automatically. The extra keyword444 arguments may not include python keywords otherwise a syntax445 error could occour. The extra keyword arguments should be given446 as python dict.447 """449 have_comma = have_comma and [True] or []450 def touch_comma():451 if have_comma:452 self.write(', ')453 else:454 have_comma.append(True)455448 # if any of the given keyword arguments is a python keyword449 # we have to make sure that no invalid call is created.450 kwarg_workaround = False451 for kwarg in chain((x.key for x in node.kwargs), extra_kwargs or ()):
1 unmodified line
453 kwarg_workaround = True454 break455456 for arg in node.args:465 touch_comma()457 self.write(', ')458 self.visit(arg, frame)459460 if not kwarg_workaround:461 for kwarg in node.kwargs:470 touch_comma()462 self.write(', ')463 self.visit(kwarg, frame)464 if extra_kwargs is not None:465 for key, value in extra_kwargs.iteritems():474 touch_comma()475 self.write('%s=%s' % (key, value))466 self.write(', %s=%s' % (key, value))467 if node.dyn_args:477 touch_comma()478 self.write('*')468 self.write(', *')469 self.visit(node.dyn_args, frame)470471 if kwarg_workaround:482 touch_comma()472 if node.dyn_kwargs is not None:484 self.write('**dict({')473 self.write(', **dict({')474 else:486 self.write('**{')475 self.write(', **{')476 for kwarg in node.kwargs:477 self.write('%r: ' % kwarg.key)478 self.visit(kwarg.value, frame)479 self.write(', ')
7 unmodified lines
487 else:488 self.write('}')489490 elif node.dyn_kwargs is not None:502 touch_comma()503 self.write('**')491 self.write(', **')492 self.visit(node.dyn_kwargs, frame)493494 def pull_locals(self, frame):495 """Pull all the references identifiers into the local scope."""
844 unmodified lines
1340 self.write(')')13411342 def visit_Call(self, node, frame, forward_caller=False):1343 if self.environment.sandboxed:1356 self.write('environment.call(')1344 self.write('environment.call(context, ')1345 else:1346 self.write('context.call(')1347 self.visit(node.node, frame)1358 self.write(self.environment.sandboxed and ', ' or '(')1348 extra_kwargs = forward_caller and {'caller': 'caller'} or None1360 self.signature(node, frame, False, extra_kwargs)1349 self.signature(node, frame, extra_kwargs)1350 self.write(')')13511352 def visit_Keyword(self, node, frame):1353 self.write(node.key + '=')
29 unmodified lines
modified:jinja2/nodes.py+4 added-6 removed
12 unmodified lines
13 :license: BSD, see LICENSE for more details.14"""15import operator16from copy import copy17from types import FunctionType17from itertools import chain, izip18from collections import deque19from jinja2.utils import Markup20
527 unmodified lines
548 obj = self.node.as_const()549550 # don't evaluate context functions551 args = [x.as_const() for x in self.args]553 if type(obj) is FunctionType:554 if getattr(obj, 'contextfunction', False):555 raise Impossible()556 elif obj.environmentfunction:557 args.insert(0, self.environment)552 if getattr(obj, 'contextfunction', False):553 raise Impossible()554 elif getattr(obj, 'environmentfunction', False):555 args.insert(0, self.environment)556557 kwargs = dict(x.as_const() for x in self.kwargs)558 if self.dyn_args is not None:559 try:
220 unmodified lines
modified:jinja2/parser.py+1 added
148 unmodified lines
149 def parse_block(self):150 node = nodes.Block(lineno=self.stream.next().lineno)151 node.name = self.stream.expect('name').value152 node.body = self.parse_statements(('name:endblock',), drop_needle=True)153 self.stream.skip_if('name:' + node.name)154 return node155156 def parse_extends(self):157 node = nodes.Extends(lineno=self.stream.next().lineno)
597 unmodified lines
modified:jinja2/runtime.py+11 added-8 removed
64 unmodified lines
65 self.environment = environment66 self.exported_vars = set()67 self.name = name6869 # bind functions to the context of environment if required70 for name, obj in parent.iteritems():71 if type(obj) is FunctionType:72 if getattr(obj, 'contextfunction', 0):73 vars[name] = partial(obj, self)74 elif getattr(obj, 'environmentfunction', 0):75 vars[name] = partial(obj, environment)7669 # create the initial mapping of blocks. Whenever template inheritance70 # takes place the runtime will update this mapping with the new blocks71 # from the template.72 self.blocks = dict((k, [v]) for k, v in blocks.iteritems())
40 unmodified lines
113 global variables.114 """115 return dict(self.parent, **self.vars)116117 def call(__self, __obj, *args, **kwargs):118 """Called by the template code to inject the current context119 or environment as first arguments. Then forwards the call to120 the object with the arguments and keyword arguments.121 """122 if getattr(__obj, 'contextfunction', 0):123 args = (__self,) + args124 elif getattr(__obj, 'environmentfunction', 0):125 args = (__self.environment,) + args126 return __obj(*args, **kwargs)127128 def _all(meth):129 proxy = lambda self: getattr(self.get_all(), meth)()130 proxy.__doc__ = getattr(dict, meth).__doc__131 proxy.__name__ = meth
315 unmodified lines
modified:jinja2/sandbox.py+2 added-2 removed
188 unmodified lines
189 obj.__class__.__name__190 ), name=argument, exc=SecurityError)191 return self.undefined(obj=obj, name=argument)192193 def call(__self, __obj, *args, **kwargs):193 def call(__self, __context, __obj, *args, **kwargs):194 """Call an object from sandboxed code."""195 # the double prefixes are to avoid double keyword argument196 # errors when proxying the call.197 if not __self.is_safe_callable(__obj):198 raise SecurityError('%r is not safely callable' % (__obj,))199 return __obj(*args, **kwargs)199 return __context.call(__obj, *args, **kwargs)200201202class ImmutableSandboxedEnvironment(SandboxedEnvironment):203 """Works exactly like the regular `SandboxedEnvironment` but does not
8 unmodified lines
modified:jinja2/utils.py+3 added-3 removed
62 unmodified lines
636465def contextfunction(f):66 """This decorator can be used to mark a callable as context callable. A67 context callable is passed the active context as first argument if it68 was directly stored in the context.67 context callable is passed the active context as first argument when68 called from the template.69 """70 f.contextfunction = True71 return f727374def environmentfunction(f):75 """This decorator can be used to mark a callable as environment callable.76 A environment callable is passed the current environment as first argument77 if it was directly stored in the context.77 when called from the template.78 """79 f.environmentfunction = True80 return f81
487 unmodified lines
modified:tests/test_syntax.py+7 added-5 removed
4 unmodified lines
56 :copyright: 2007 by Armin Ronacher.7 :license: BSD, see LICENSE for more details.8"""9from py.test import raises10from jinja2 import Environment, DictLoader11from jinja2.exceptions import TemplateSyntaxError1213
129 unmodified lines
143 (False, '*foo, **bar')144 ]145 for should_fail, sig in tests:146 if should_fail:146 try:147 print env.from_string('{{ foo(%s) }}' % sig)148 except TemplateSyntaxError:149 continue150 assert False, 'expected syntax error'147 raises(TemplateSyntaxError, env.from_string, '{{ foo(%s) }}' % sig)148 else:149 env.from_string('foo(%s)' % sig)150151
5 unmodified lines
157158def test_trailing_comma(env):159 tmpl = env.from_string(TRAILINGCOMMA)160 assert tmpl.render().lower() == '(1, 2)|[1, 2]|{1: 2}'161162163def test_block_end_name(env):164 env.from_string('{% block foo %}...{% endblock foo %}')165 raises(TemplateSyntaxError, env.from_string, '{% block x %}{% endblock y %}')