zoukankan      html  css  js  c++  java
  • flask之Jinja2

    Jinja2 is a library found at http://jinja.pocoo.org/; you can use it to produce formatted text with bundled logic. 

    Imagine a variable x has its value set
    to <b>b</b>. If auto-escaping is enabled, {{ x }} in a template would print the string as given. If auto-escaping 

    is off, which is the Jinja2 default (Flask's default is on), the resulting text would be b. 

    Double curly braces are a delimiter that allows you to evaluate a variable or function from the provided context and print it into the template: 

    from jinja2 import Template

       # create the template

       t = Template("{{ variable }}")

    # – Built-in Types –

    t.render(variable='hello you')

    >> u"hello you"

    t.render(variable=100)

    >> u"100"

    # you can evaluate custom classes instances

    class A(object):

      def __str__(self):

        return "__str__"

      def __unicode__(self):

        return u"__unicode__"

      def __repr__(self):

        return u"__repr__"

    # – Custom Objects Evaluation –

    # __unicode__ has the highest precedence in evaluation

    # followed by __str__ and __repr__

    t.render(variable=A())

    >> u"__unicode__"

    First, we evaluate a string and then an integer. Both result in a unicode string. If we evaluate a class of our own, we must make sure there is a __unicode__ method de ned, as it is called during the evaluation. If a __unicode__ method is not de ned, the evaluation falls back to __str__ and __repr__, sequentially. This is easy. 

    from jinja2 import Template

       # create the template

       t = Template("{{ fnc() }}")

       t.render(fnc=lambda: 10)

       >> u"10"

       # evaluating a function with argument

       t = Template("{{ fnc(x) }}")

       t.render(fnc=lambda v: v, x='20')

       >> u"20"

       t = Template("{{ fnc(v=30) }}")

       t.render(fnc=lambda v: v)

       >> u"30"

    inja2 also has the curly braces/percentage delimiter, which uses the notation {% stmt %} and is used to execute statements, which may be a control statement or not. Its usage depends on the statement, where control statements have the following notation: 

    {% stmt %}

    {% endstmt %}

    A last delimiter you should know is{# comments go here #}.Itisamulti-line delimiter used to declare comments. 

    As a design decision to avoid confusion, all Jinja2 templates have a lowercase alias for True, False, and None.
    By the way, lowercase syntax is the preferred way to go. 

    When building HTML lists, it's a common requirement to mark each list item
    in alternating colors in order to improve readability or mark the rst or/and
    last item with some special markup. Those behaviors can be achieved in a Jinja2 for-loop through access to a loop variable available inside the block context. Let's see some examples: 

       {% for i in ['a', 'b', 'c', 'd'] %}

       {% if loop.first %}This is the first iteration{% endif %}

       {% if loop.last %}This is the last iteration{% endif %}

    With Jinja2, the else block is executed when the for iterable is empty. 

    the Jinja2 for loop does not support break or continue. Instead, to achieve the expected behavior, you should use loop ltering as follows: 

       {% for i in [1, 2, 3, 4, 5] if i > 2 %}

       value: {{ i }}; loop.index: {{ loop.index }}

       {%- endfor %}

    You should consider that condition as a real list lter, as the index itself is only counted per iteration.

    do you see the dash in {%-? It tells the renderer that there should be no empty new lines before the tag at each iteration. 

    block and extends always work together. The rst is used to de ne "overwritable" blocks in a template, while the second de nes a parent template that has blocks 

    he include statement is probably the easiest statement so far. It allows you to render a template inside another in a very easy fashion. 

    Finally, we have the set statement. It allows you to de ne variables for inside the template context. Its use is pretty simple: 

       {% set x = 10 %}

       {{ x }}

       {% set x, y, z = 10, 5+5, "home" %}

       {{ x }} - {{ y }} - {{ z }}

    Macros are the closest to coding you'll get inside Jinja2 templates. The macro de nition and usage are similar to plain Python functions 

    {% macro input(name, value='', label='') %}

       {% if label %}

       <label for='{{ name }}'>{{ label }}</label>

       {% endif %}

       <input id='{{ name }}' name='{{ name }}' value='{{ value }}'></input>

       {% endmacro %}

    we could even rename our input macro like this: 

    {% from 'formfield.html' import input as field_input %} You can also import formfield as a module and use it as follows: 

       {% import 'formfield.html' as formfield %}

    When using macros, there is a special case where you want to allow any named argument to be passed into the macro, as you would in a Python function (for example, **kwargs). With Jinja2 macros, these values are, by default, available in a kwargs dictionary that does not need to be explicitly de ned in the macro signature. 

    kwargs is available even though you did not de ne a kwargs argument in the macro signature. 

    • Extensions are the way Jinja2 allows you to extend its vocabulary. Extensions are not enabled by default, so you can enable an extension only when and if you need, and start using it without much trouble:
         env = Environment(extensions=['jinja2.ext.do',
    •     'jinja2.ext.with_'])

    • In the preceding code, we have an example where you create an environment with two extensions enabled: do and with.

    % set x = {1:'home', '2':'boat'} %}

       {% do x.update({3: 'bar'}) %}

       {%- for key,value in x.items() %}

       {{ key }} - {{ value }}

    {%- endfor %} 

    In the preceding example, we create the x variable with a dictionary, then we update it with {3: 'bar'}. You don't usually need to use the do extension but, when you do, a lot of coding is saved. 

    The with extension is also very simple. You use it whenever you need to create block scoped variables. Imagine you have a value you need cached in a variable for a brief moment; this would be a good use case. Let's see an example: 

       {% with age = user.get_age() %}

       My age: {{ age }}

       {% endwith %}

       My age: {{ age }}{# no value here #}

    As seen in the example, age exists only inside the with block. Also, variables set inside a with block will only exist inside it. For example: 

       {% with %}

       {% set count = query.count() %}

       Current Stock: {{ count }}

       Diff: {{ prev_count - count }}

       {% endwith %}

       {{ count }} {# empty value #}

    Filters are a marvelous thing about Jinja2! This tool allows you to process a constant or variable before printing it to the template. The goal is to implement the formatting you want, strictly in the template. 

    To use a lter, just call it using the pipe operator like this: 

       {% set name = 'junior' %}

       {{ name|capitalize }} {# output is Junior #}

    {{ ['Adam', 'West']|join(' ') }} {# output is Adam West #}

    {# prints default value if input is undefined #}

       {{ x|default('no opinion') }}

       {# prints default value if input evaluates to false #}

       {{ none|default('no opinion', true) }}

       {# prints input as it was provided #}

       {{ 'some opinion'|default('no opinion') }}

       {# you can use a filter inside a control statement #}

       {# sort by key case-insensitive #}

       {% for key in {'A':3, 'b':2, 'C':1}|dictsort %}{{ key }}{% endfor %}

       {# sort by key case-sensitive #}

       {% for key in {'A':3, 'b':2, 'C':1}|dictsort(true) %}{{ key }}{%

       endfor %}

       {# sort by value #}

       {% for key in {'A':3, 'b':2, 'C':1}|dictsort(false, 'value') %}{{ key

       }}{% endfor %}

       {{ [3, 2, 1]|first }} - {{ [3, 2, 1]|last }}

       {{ [3, 2, 1]|length }} {# prints input length #}

       {# same as in python #}

       {{ '%s, =D'|format("I'm John") }}

       {{ "He has two daughters"|replace('two', 'three') }}

       {# safe prints the input without escaping it first#}

       {{ '<input name="stuff" />'|safe }}

       {{ "there are five words here"|wordcount }}

    As Flask manages the Jinja2 environment for you, you don't have to worry about creating le loaders and stuff like that. One thing you should be aware of, though, is that, because you don't instantiate the Jinja2 environment yourself, you can't really pass to the class constructor, the extensions you want to activate. 

    To activate an extension, add it to Flask during the application setup as follows: 

       from flask import Flask

       app = Flask(__name__)

       app.jinja_env.add_extension('jinja2.ext.do')  # or jinja2.ext.with_

       if __name__ == '__main__':

    app.run() 

    Now, what if you want all your views to have a speci c value in their context, like a version value—some special code or function; how would you do it? Flask offers you the context_processor decorator to accomplish that. You just have to annotate a function that returns a dictionary and you're ready to go. For example: 

       from flask import Flask, render_response

       app = Flask(__name__)

       @app.context_processor

       def luck_processor():

         from random import randint

         def lucky_number():

              return randint(1, 10)

         return dict(lucky_number=lucky_number)

       @app.route("/")

       def hello():

         # lucky_number will be available in the index.html context by

       default

         return render_template("index.html")

  • 相关阅读:
    MySQL学习-- UNION与UNION ALL
    图解MySQL 内连接、外连接、左连接、右连接、全连接……太多了
    mysql的三种连接方式
    Spring Boot MyBatis配置多种数据库
    @Value注解分类解析
    SpringBoot启动报错Failed to determine a suitable driver class
    idea启动报错:Access denied for user 'root '@'192.168.100.XXX' (using password: YES)
    QStandardItemModel的data线程安全(在插入数据时,临时禁止sizeHint去读model中的data)
    ubuntu 交叉编译qt 5.7 程序到 arm 开发板
    继承QWidget的派生类控件不能设置QSS问题解决(使用style()->drawPrimitive(QStyle::PE_Widget,也就是画一个最简单最原始的QWidget,不要牵扯其它这么多东西)
  • 原文地址:https://www.cnblogs.com/zxpo/p/5411011.html
Copyright © 2011-2022 走看看