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
Provenance
- Commit
fd31049- Tree
e1715b4- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
9f258ff
10 files changed+180 added−48 removed
added:docs/faq.rst+123 added
1+Frequently Asked Questions2+==========================3+4+This page answers some of the often asked questions about Jinja.5+6+.. highlight:: html+jinja7+8+9+Why is it called Jinja?10+-----------------------11+12+The name Jinja was chosen because it's the name of a Japanese temple and13+temple and template share a similar pronunciation. It is not named after14+the capital city of Uganda.15+16+How fast is it?17+---------------18+19+We really hate benchmarks especially since they don't reflect much. The20+performance of a template depends on many factors and you would have to21+benchmark different engines in different situations. The benchmarks from the22+testsuite show that Jinja2 has a similar performance to `Mako`_ and is more23+than 20 times faster than Django's template engine or Genshi. These numbers24+should be taken with tons of salt!25+26+.. _Mako: http://www.makotemplates.org/27+28+How Compatible is Jinja2 with Django?29+-------------------------------------30+31+The default syntax of Jinja2 matches Django syntax in many ways. However32+this similarity doesn't mean that you can use a Django template unmodified33+in Jinja2. For example filter arguments use a function call syntax rather34+than a colon to separate filter name and arguments. Additionally the35+extension interface in Jinja is fundamentally different from the Django one36+which means that your custom tags won't work any longer.37+38+Generally speaking you will use much less custom extensions as the Jinja39+template system allows you to use a certain subset of Python expressions40+which can replace most Django extensions. For example instead of using41+something like this::42+43+ {% load comments %}44+ {% get_latest_comments 10 as latest_comments %}45+ {% for comment in latest_comments %}46+ ...47+ {% endfor %}48+49+You will most likely provide an object with attributes to retrieve50+comments from the database::51+52+ {% for comment in models.comments.latest(10) %}53+ ...54+ {% endfor %}55+56+Or directly provide the model for quick testing::57+58+ {% for comment in Comment.objects.order_by('-pub_date')[:10] %}59+ ...60+ {% endfor %}61+62+Please keep in mind that even though you may put such things into templates63+it still isn't a good idea. Queries should go into the view code and now64+the template!65+66+Isn't it a terrible idea to put Logic into Templates?67+-----------------------------------------------------68+69+Without a doubt you should try to remove as much logic from templates as70+possible. But templates without any logic mean that you have to do all71+the processing in the code which is boring and stupid. A template engine72+that does that is shipped with Python and called `string.Template`. Comes73+without loops and if conditions and is by far the fastest template engine74+you can get for Python.75+76+So some amount of logic is required in templates to keep everyone happy.77+And Jinja leaves it pretty much to you how much logic you want to put into78+templates. There are some restrictions in what you can do and what not.79+80+Jinja2 neither allows you to put arbitrary Python code into templates nor81+does it allow all Python expressions. The operators are limited to the82+most common ones and more advanced expressions such as list comprehensions83+and generator expressions are not supported. This keeps the template engine84+easier to maintain and templates more readable.85+86+Why is Autoescaping not the Default?87+------------------------------------88+89+There are multiple reasons why automatic escaping is not the default mode90+and also not the recommended one. While automatic escaping of variables91+means that you will less likely have an XSS problem it also causes a huge92+amount of extra processing in the template engine which can cause serious93+performance problems. As Python doesn't provide a way to mark strings as94+unsafe Jinja has to hack around that limitation by providing a custom95+string class (the :class:`Markup` string) that safely interacts with safe96+and unsafe strings.97+98+With explicit escaping however the template engine doesn't have to perform99+any safety checks on variables. Also a human knows not to escape integers100+or strings that may never contain characters one has to escape or already101+HTML markup. For example when iterating over a list over a table of102+integers and floats for a table of statistics the template designer can103+omit the escaping because he knows that integers or floats don't contain104+any unsafe parameters.105+106+Additionally Jinja2 is a general purpose template engine and not only used107+for HTML/XML generation. For example you may generate LaTeX, emails,108+CSS, JavaScript, or configuration files.109+110+Why is the Context immutable?111+-----------------------------112+113+When writing a :func:`contextfunction` or something similar you may have114+noticed that the context tries to stop you from modifying it. If you have115+managed to modify the context by using an internal context API you may116+have noticed that changes in the context don't seem to be visible in the117+template. The reason for this is that Jinja uses the context only as118+primary data source for template variables for performance reasons.119+120+If you want to modify the context write a function that returns a variable121+instead that one can assign to a variable by using set::122+123+ {% set comments = get_latest_comments() %}modified:docs/index.rst+1 added
15 unmodified lines16 integration17 switching18 tricks19 20+ faq21 changelog22 23 If you can't find the information you're looking for, have a look at the24 index of try to find it using the search function:3 unmodified linesmodified:docs/templates.rst+15 added
324 unmodified lines325 {{ super() }}326 {% endblock %}327 328 329+Named Block End-Tags330+~~~~~~~~~~~~~~~~~~~~331+332+Jinja2 allows you to put the name of the block after the end tag for better333+readability::334+335+ {% block sidebar %}336+ {% block inner_sidebar %}337+ ...338+ {% endblock inner_sidebar %}339+ {% endblock sidebar %}340+341+However the name after the `endblock` word must match the block name.342+343+344 HTML Escaping345 -------------346 347 When generating HTML from templates, there's always a risk that a variable will717 unmodified linesmodified:jinja2/compiler.py+13 added-24 removed
436 unmodified lines437 if node is not None and node.lineno != self._last_line:438 self._write_debug_info = node.lineno439 self._last_line = node.lineno440 441- 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)455-448 # 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 line453 kwarg_workaround = True454 break455 456 for arg in node.args:465- touch_comma()457+ self.write(', ')458 self.visit(arg, frame)459 460 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)470 471 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 lines487 else:488 self.write('}')489 490 elif node.dyn_kwargs is not None:502- touch_comma()503- self.write('**')491+ self.write(', **')492 self.visit(node.dyn_kwargs, frame)493 494 def pull_locals(self, frame):495 """Pull all the references identifiers into the local scope."""844 unmodified lines1340 self.write(')')1341 1342 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(')')1351 1352 def visit_Keyword(self, node, frame):1353 self.write(node.key + '=')29 unmodified linesmodified:jinja2/nodes.py+4 added-6 removed
12 unmodified lines13 :license: BSD, see LICENSE for more details.14 """15 import operator16 from copy import copy17-from types import FunctionType17 from itertools import chain, izip18 from collections import deque19 from jinja2.utils import Markup20 527 unmodified lines548 obj = self.node.as_const()549 550 # 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)556 557 kwargs = dict(x.as_const() for x in self.kwargs)558 if self.dyn_args is not None:559 try:220 unmodified linesmodified:jinja2/parser.py+1 added
148 unmodified lines149 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 node155 156 def parse_extends(self):157 node = nodes.Extends(lineno=self.stream.next().lineno)597 unmodified linesmodified:jinja2/runtime.py+11 added-8 removed
64 unmodified lines65 self.environment = environment66 self.exported_vars = set()67 self.name = name68 69- # 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)76-69 # 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 lines113 global variables.114 """115 return dict(self.parent, **self.vars)116 117+ 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)127+128 def _all(meth):129 proxy = lambda self: getattr(self.get_all(), meth)()130 proxy.__doc__ = getattr(dict, meth).__doc__131 proxy.__name__ = meth315 unmodified linesmodified:jinja2/sandbox.py+2 added-2 removed
188 unmodified lines189 obj.__class__.__name__190 ), name=argument, exc=SecurityError)191 return self.undefined(obj=obj, name=argument)192 193- 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)200 201 202 class ImmutableSandboxedEnvironment(SandboxedEnvironment):203 """Works exactly like the regular `SandboxedEnvironment` but does not8 unmodified linesmodified:jinja2/utils.py+3 added-3 removed
62 unmodified lines63 64 65 def 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 f72 73 74 def 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 linesmodified:tests/test_syntax.py+7 added-5 removed
4 unmodified lines5 6 :copyright: 2007 by Armin Ronacher.7 :license: BSD, see LICENSE for more details.8 """9+from py.test import raises10 from jinja2 import Environment, DictLoader11 from jinja2.exceptions import TemplateSyntaxError12 13 129 unmodified lines143 (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)150 151 5 unmodified lines157 158 def test_trailing_comma(env):159 tmpl = env.from_string(TRAILINGCOMMA)160 assert tmpl.render().lower() == '(1, 2)|[1, 2]|{1: 2}'161+162+163+def test_block_end_name(env):164+ env.from_string('{% block foo %}...{% endblock foo %}')165+ raises(TemplateSyntaxError, env.from_string, '{% block x %}{% endblock y %}')