Current File : //usr/share/doc/python-jinja2-2.7.2/html/faq.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>Frequently Asked Questions &mdash; Jinja2 2.7.2 documentation</title>
    
    <link rel="stylesheet" href="_static/jinja.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '',
        VERSION:     '2.7.2',
        COLLAPSE_INDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>
    <script type="text/javascript" src="_static/jquery.js"></script>
    <script type="text/javascript" src="_static/underscore.js"></script>
    <script type="text/javascript" src="_static/doctools.js"></script>
    <link rel="top" title="Jinja2 2.7.2 documentation" href="index.html" />
    <link rel="next" title="Jinja2 Changelog" href="changelog.html" />
    <link rel="prev" title="Tips and Tricks" href="tricks.html" /> 
  </head>
  <body>
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="changelog.html" title="Jinja2 Changelog"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="tricks.html" title="Tips and Tricks"
             accesskey="P">previous</a> |</li>
        <li><a href="index.html">Jinja2 2.7.2 documentation</a> &raquo;</li> 
      </ul>
    </div>  

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body">
            
  <div class="section" id="frequently-asked-questions">
<h1>Frequently Asked Questions<a class="headerlink" href="#frequently-asked-questions" title="Permalink to this headline">¶</a></h1>
<p>This page answers some of the often asked questions about Jinja.</p>
<div class="section" id="why-is-it-called-jinja">
<h2>Why is it called Jinja?<a class="headerlink" href="#why-is-it-called-jinja" title="Permalink to this headline">¶</a></h2>
<p>The name Jinja was chosen because it&#8217;s the name of a Japanese temple and
temple and template share a similar pronunciation.  It is not named after
the city in Uganda.</p>
</div>
<div class="section" id="how-fast-is-it">
<h2>How fast is it?<a class="headerlink" href="#how-fast-is-it" title="Permalink to this headline">¶</a></h2>
<p>We really hate benchmarks especially since they don&#8217;t reflect much.  The
performance of a template depends on many factors and you would have to
benchmark different engines in different situations.  The benchmarks from the
testsuite show that Jinja2 has a similar performance to <a class="reference external" href="http://www.makotemplates.org/">Mako</a> and is between
10 and 20 times faster than Django&#8217;s template engine or Genshi.  These numbers
should be taken with tons of salt as the benchmarks that took these numbers
only test a few performance related situations such as looping.  Generally
speaking the performance of a template engine doesn&#8217;t matter much as the
usual bottleneck in a web application is either the database or the application
code.</p>
</div>
<div class="section" id="how-compatible-is-jinja2-with-django">
<h2>How Compatible is Jinja2 with Django?<a class="headerlink" href="#how-compatible-is-jinja2-with-django" title="Permalink to this headline">¶</a></h2>
<p>The default syntax of Jinja2 matches Django syntax in many ways.  However
this similarity doesn&#8217;t mean that you can use a Django template unmodified
in Jinja2.  For example filter arguments use a function call syntax rather
than a colon to separate filter name and arguments.  Additionally the
extension interface in Jinja is fundamentally different from the Django one
which means that your custom tags won&#8217;t work any longer.</p>
<p>Generally speaking you will use much less custom extensions as the Jinja
template system allows you to use a certain subset of Python expressions
which can replace most Django extensions.  For example instead of using
something like this:</p>
<div class="highlight-html+jinja"><div class="highlight"><pre><span class="cp">{%</span> <span class="k">load</span> <span class="nv">comments</span> <span class="cp">%}</span>
<span class="cp">{%</span> <span class="k">get_latest_comments</span> <span class="m">10</span> <span class="k">as</span> <span class="nv">latest_comments</span> <span class="cp">%}</span>
<span class="cp">{%</span> <span class="k">for</span> <span class="nv">comment</span> <span class="k">in</span> <span class="nv">latest_comments</span> <span class="cp">%}</span>
    ...
<span class="cp">{%</span> <span class="k">endfor</span> <span class="cp">%}</span>
</pre></div>
</div>
<p>You will most likely provide an object with attributes to retrieve
comments from the database:</p>
<div class="highlight-html+jinja"><div class="highlight"><pre><span class="cp">{%</span> <span class="k">for</span> <span class="nv">comment</span> <span class="k">in</span> <span class="nv">models.comments.latest</span><span class="o">(</span><span class="m">10</span><span class="o">)</span> <span class="cp">%}</span>
    ...
<span class="cp">{%</span> <span class="k">endfor</span> <span class="cp">%}</span>
</pre></div>
</div>
<p>Or directly provide the model for quick testing:</p>
<div class="highlight-html+jinja"><div class="highlight"><pre><span class="cp">{%</span> <span class="k">for</span> <span class="nv">comment</span> <span class="k">in</span> <span class="nv">Comment.objects.order_by</span><span class="o">(</span><span class="s1">&#39;-pub_date&#39;</span><span class="o">)[:</span><span class="m">10</span><span class="o">]</span> <span class="cp">%}</span>
    ...
<span class="cp">{%</span> <span class="k">endfor</span> <span class="cp">%}</span>
</pre></div>
</div>
<p>Please keep in mind that even though you may put such things into templates
it still isn&#8217;t a good idea.  Queries should go into the view code and not
the template!</p>
</div>
<div class="section" id="isn-t-it-a-terrible-idea-to-put-logic-into-templates">
<h2>Isn&#8217;t it a terrible idea to put Logic into Templates?<a class="headerlink" href="#isn-t-it-a-terrible-idea-to-put-logic-into-templates" title="Permalink to this headline">¶</a></h2>
<p>Without a doubt you should try to remove as much logic from templates as
possible.  But templates without any logic mean that you have to do all
the processing in the code which is boring and stupid.  A template engine
that does that is shipped with Python and called <cite>string.Template</cite>.  Comes
without loops and if conditions and is by far the fastest template engine
you can get for Python.</p>
<p>So some amount of logic is required in templates to keep everyone happy.
And Jinja leaves it pretty much to you how much logic you want to put into
templates.  There are some restrictions in what you can do and what not.</p>
<p>Jinja2 neither allows you to put arbitrary Python code into templates nor
does it allow all Python expressions.  The operators are limited to the
most common ones and more advanced expressions such as list comprehensions
and generator expressions are not supported.  This keeps the template engine
easier to maintain and templates more readable.</p>
</div>
<div class="section" id="why-is-autoescaping-not-the-default">
<h2>Why is Autoescaping not the Default?<a class="headerlink" href="#why-is-autoescaping-not-the-default" title="Permalink to this headline">¶</a></h2>
<p>There are multiple reasons why automatic escaping is not the default mode
and also not the recommended one.  While automatic escaping of variables
means that you will less likely have an XSS problem it also causes a huge
amount of extra processing in the template engine which can cause serious
performance problems.  As Python doesn&#8217;t provide a way to mark strings as
unsafe Jinja has to hack around that limitation by providing a custom
string class (the <tt class="xref py py-class docutils literal"><span class="pre">Markup</span></tt> string) that safely interacts with safe
and unsafe strings.</p>
<p>With explicit escaping however the template engine doesn&#8217;t have to perform
any safety checks on variables.  Also a human knows not to escape integers
or strings that may never contain characters one has to escape or already
HTML markup.  For example when iterating over a list over a table of
integers and floats for a table of statistics the template designer can
omit the escaping because he knows that integers or floats don&#8217;t contain
any unsafe parameters.</p>
<p>Additionally Jinja2 is a general purpose template engine and not only used
for HTML/XML generation.  For example you may generate LaTeX, emails,
CSS, JavaScript, or configuration files.</p>
</div>
<div class="section" id="why-is-the-context-immutable">
<h2>Why is the Context immutable?<a class="headerlink" href="#why-is-the-context-immutable" title="Permalink to this headline">¶</a></h2>
<p>When writing a <tt class="xref py py-func docutils literal"><span class="pre">contextfunction()</span></tt> or something similar you may have
noticed that the context tries to stop you from modifying it.  If you have
managed to modify the context by using an internal context API you may
have noticed that changes in the context don&#8217;t seem to be visible in the
template.  The reason for this is that Jinja uses the context only as
primary data source for template variables for performance reasons.</p>
<p>If you want to modify the context write a function that returns a variable
instead that one can assign to a variable by using set:</p>
<div class="highlight-html+jinja"><div class="highlight"><pre><span class="cp">{%</span> <span class="k">set</span> <span class="nv">comments</span> <span class="o">=</span> <span class="nv">get_latest_comments</span><span class="o">()</span> <span class="cp">%}</span>
</pre></div>
</div>
</div>
<div class="section" id="my-tracebacks-look-weird-what-s-happening">
<h2>My tracebacks look weird.  What&#8217;s happening?<a class="headerlink" href="#my-tracebacks-look-weird-what-s-happening" title="Permalink to this headline">¶</a></h2>
<p>If the debugsupport module is not compiled and you are using a Python
installation without ctypes (Python 2.4 without ctypes, Jython or Google&#8217;s
AppEngine) Jinja2 is unable to provide correct debugging information and
the traceback may be incomplete.  There is currently no good workaround
for Jython or the AppEngine as ctypes is unavailable there and it&#8217;s not
possible to use the debugsupport extension.</p>
<p>If you are working in the Google Appengine development server you can
whitelist the ctypes module to restore the tracebacks.  This however won&#8217;t
work in production environments:</p>
<div class="highlight-html+jinja"><div class="highlight"><pre>import os
if os.environ.get(&#39;SERVER_SOFTWARE&#39;, &#39;&#39;).startswith(&#39;Dev&#39;):
    from google.appengine.tools.dev_appserver import HardenedModulesHook
    HardenedModulesHook._WHITE_LIST_C_MODULES += [&#39;_ctypes&#39;, &#39;gestalt&#39;]
</pre></div>
</div>
<p>Credit for this snippet goes to <a class="reference external" href="http://stackoverflow.com/questions/3086091/debug-jinja2-in-google-app-engine/3694434#3694434">Thomas Johansson</a></p>
</div>
<div class="section" id="why-is-there-no-python-2-3-support">
<h2>Why is there no Python 2.3 support?<a class="headerlink" href="#why-is-there-no-python-2-3-support" title="Permalink to this headline">¶</a></h2>
<p>Python 2.3 is missing a lot of features that are used heavily in Jinja2.  This
decision was made as with the upcoming Python 2.6 and 3.0 versions it becomes
harder to maintain the code for older Python versions.  If you really need
Python 2.3 support you either have to use <a class="reference external" href="http://jinja.pocoo.org/1/">Jinja 1</a> or other templating
engines that still support 2.3.</p>
</div>
<div class="section" id="my-macros-are-overridden-by-something">
<h2>My Macros are overridden by something<a class="headerlink" href="#my-macros-are-overridden-by-something" title="Permalink to this headline">¶</a></h2>
<p>In some situations the Jinja scoping appears arbitrary:</p>
<p>layout.tmpl:</p>
<div class="highlight-jinja"><div class="highlight"><pre><span class="cp">{%</span> <span class="k">macro</span> <span class="nv">foo</span><span class="o">()</span> <span class="cp">%}</span><span class="x">LAYOUT</span><span class="cp">{%</span> <span class="k">endmacro</span> <span class="cp">%}</span><span class="x"></span>
<span class="cp">{%</span> <span class="k">block</span> <span class="nv">body</span> <span class="cp">%}{%</span> <span class="k">endblock</span> <span class="cp">%}</span><span class="x"></span>
</pre></div>
</div>
<p>child.tmpl:</p>
<div class="highlight-jinja"><div class="highlight"><pre><span class="cp">{%</span> <span class="k">extends</span> <span class="s1">&#39;layout.tmpl&#39;</span> <span class="cp">%}</span><span class="x"></span>
<span class="cp">{%</span> <span class="k">macro</span> <span class="nv">foo</span><span class="o">()</span> <span class="cp">%}</span><span class="x">CHILD</span><span class="cp">{%</span> <span class="k">endmacro</span> <span class="cp">%}</span><span class="x"></span>
<span class="cp">{%</span> <span class="k">block</span> <span class="nv">body</span> <span class="cp">%}{{</span> <span class="nv">foo</span><span class="o">()</span> <span class="cp">}}{%</span> <span class="k">endblock</span> <span class="cp">%}</span><span class="x"></span>
</pre></div>
</div>
<p>This will print <tt class="docutils literal"><span class="pre">LAYOUT</span></tt> in Jinja2.  This is a side effect of having
the parent template evaluated after the child one.  This allows child
templates passing information to the parent template.  To avoid this
issue rename the macro or variable in the parent template to have an
uncommon prefix.</p>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar">
        <div class="sphinxsidebarwrapper"><p class="logo"><a href="index.html">
  <img class="logo" src="_static/jinja-small.png" alt="Logo"/>
</a></p>
  <h3><a href="index.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Frequently Asked Questions</a><ul>
<li><a class="reference internal" href="#why-is-it-called-jinja">Why is it called Jinja?</a></li>
<li><a class="reference internal" href="#how-fast-is-it">How fast is it?</a></li>
<li><a class="reference internal" href="#how-compatible-is-jinja2-with-django">How Compatible is Jinja2 with Django?</a></li>
<li><a class="reference internal" href="#isn-t-it-a-terrible-idea-to-put-logic-into-templates">Isn&#8217;t it a terrible idea to put Logic into Templates?</a></li>
<li><a class="reference internal" href="#why-is-autoescaping-not-the-default">Why is Autoescaping not the Default?</a></li>
<li><a class="reference internal" href="#why-is-the-context-immutable">Why is the Context immutable?</a></li>
<li><a class="reference internal" href="#my-tracebacks-look-weird-what-s-happening">My tracebacks look weird.  What&#8217;s happening?</a></li>
<li><a class="reference internal" href="#why-is-there-no-python-2-3-support">Why is there no Python 2.3 support?</a></li>
<li><a class="reference internal" href="#my-macros-are-overridden-by-something">My Macros are overridden by something</a></li>
</ul>
</li>
</ul>
<h3>Related Topics</h3>
<ul>
  <li><a href="index.html">Documentation overview</a><ul>
      <li>Previous: <a href="tricks.html" title="previous chapter">Tips and Tricks</a></li>
      <li>Next: <a href="changelog.html" title="next chapter">Jinja2 Changelog</a></li>
  </ul></li>
</ul>
  <h3>This Page</h3>
  <ul class="this-page-menu">
    <li><a href="_sources/faq.txt"
           rel="nofollow">Show Source</a></li>
  </ul>
<div id="searchbox" style="display: none">
  <h3>Quick search</h3>
    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    <p class="searchtip" style="font-size: 90%">
    Enter search terms or a module, class or function name.
    </p>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>
    <div class="footer">
      &copy; Copyright 2008, Armin Ronacher.
      Created using <a href="http://sphinx.pocoo.org/">Sphinx</a>.
    </div>
  </body>
</html>
blog

blog

1win официальный сайт букмекера — Обзор и зеркало для входа.1211

Содержимое 1win Официальный Сайт Букмекера Обзор и Зеркало для Входа Преимущества 1win Зеркало для входа Преимущества и Функции 1win Бонусы и Промокоды 1win официальный сайт букмекера — Обзор и зеркало для входа В мире ставок и азарта 1вин является одним из самых популярных букмекеров, предлагающих широкий спектр услуг для игроков …

Read More »

Meilleur Casino en Ligne 2025 – Sites Fiables.3715 (2)

Содержимое Les Critères de Sélection La Légalité La Sécurité La Gamme de Jeux La Réputation Les Offres de Bonus Les Meilleurs Casinos en Ligne Fiables Les Avantages et les Inconvénients Les Avantages Les Inconvénients Conseils pour Jouer de Manière Sûre au Meilleur Casino en Ligne Meilleur Casino en Ligne 2025 …

Read More »

Pin Up Casino — ваше надёжное место для больших выигрышей в Пин Ап Казино Онлайн.265

Содержимое Удобство и безопасность в Pin Up Casino Большой выбор игр и бонусов в Pin Up Casino Pin Up Casino — ваше надёжное место для больших выигрышей в Пин Ап Казино Онлайн В мире онлайн-казино есть много вариантов, но не все они могут сравниться с pin up Casino. Это надёжное …

Read More »

1win — скачать приложение букмекерской конторы.2814 (2)

Содержимое Установка приложения 1win Шаг 1: Скачать приложение Шаг 2: Установка приложения Функциональность приложения 1win Биржевые ставки Личный кабинет Преимущества использования приложения 1win Как скачать приложение 1win Шаги для скачивания 1win apk Обзор безопасности приложения 1win Защита данных Защита от мошенничества 1win — скачать приложение букмекерской конторы В мире ставок …

Read More »

1win — скачать приложение букмекерской конторы.1432 (2)

Содержимое Установка и регистрация 1win Шаги регистрации на 1win Основные функции и преимущества 1win apk Удобство и доступность Бонусы и акции 1win — скачать приложение букмекерской конторы В мире ставок и азарта 1вин является одним из самых популярных букмекерских контор, которые предлагают своим клиентам широкий спектр услуг и возможностей для …

Read More »

1win — регистрация в букмекерской конторе 1вин.3785

1win — регистрация в букмекерской конторе 1вин ▶️ ИГРАТЬ Содержимое Шаги регистрации в 1win Как начать играть и получать бонусы в 1win В мире ставок и азарта 1вин – это имя, которое ассоциируется с надежностью, быстротой и комфортной игрой. Букмекерская контора 1вин – это место, где можно сделать ставку и …

Read More »

Pin Up Casino Azərbaycan.984

Содержимое Quruluş və Xidmətlər Qeydiyyat və Oyunlar Pin Up Casino Azərbaycan Pin Up Casino Azərbaycan – bu pinap az və pinup casino tərəfindən təqdim olunmuş, Azərbaycanlılar üçün məşhur və müraciətçilərə uyğun qızıl qalılıq casino. Bu platforma, pin up casino tərəfindən hazırlanmış və Azərbaycan dili ilə tətbiq edilmişdir. Pin Up Casino …

Read More »

Казино Официальный сайт Pin Up Casino играть онлайн – Вход, Зеркало.194

Пин Ап Казино Официальный сайт | Pin Up Casino играть онлайн – Вход, Зеркало ▶️ ИГРАТЬ Содержимое Pin Up Casino – Официальный Сайт Преимущества официального сайта Pin Up Casino Играть Онлайн – Вход, Зеркало В современном мире азартных игр, где каждый день появляются новые онлайн-казино, сложно найти надежный и проверенный …

Read More »