zoukankan      html  css  js  c++  java
  • Jinja2基本操作


    变量:  

      JinJia2能识别许许多多python类型中的变量,例如

    <p> 获取字典中的值: {{ Dict['Key'] }} </p>
    <p> 获取列表中的值: {{ List[2] }} </p>
    <p> 获取对象方法: {{ obj.Method() }} </p>
    

    过滤器:

      

    过滤器名称   说明 
     safe  渲染时不使用转义 
     capitalize 将值的首字母转换成大写的形式,其他的字母转换为小写 
     lower 把值转换成为小写 
     upper  把值转换成大写 
     title 把值中每个单词的首字母都转换成大写的形式 
     trim 把值的空格去掉 
     striptags 渲染之前把值中所有的HTML标签都删除 

    基本语句:

      if 语句

    1  {% if condation%}
    2      第一分支语句
    3  {% else %}
    4      第二分支语句
    5  {% endif %}

      for语句

    1 { % for comment in comments %}
    2 <li>{%commet%}</li>
    3 {% endfor %}

      宏: 宏的使用方法类似于声明一个函数,可以将常用的功能封装起来,放在单独的文件当中,然后再需要使用的位置进行引用即可

    1 {% macro render_comment(comment) %}
    2 <li> {{ comment }} </li>
    3 {% endmacro %}
    4 
    5 {% for comment in comments %}
    6 {{ render_comment(comment) }}
    7 {% endif %}

      在其他文件中的宏的引用

    1 {% import 'macros.html' as macros %}
    2 {% for comment in comments %}
    3 {{ macros.render_comment(comment) }}
    4 {% endfor %}

      需要在多处重复使用的模板代码片段可以写入单独的文件当中,再包含所在所有模板中,以避免重复

    1 {% include ‘common.html’ %}

      另一种代码复用的方式是模板继承,它类似于python代码中的继承。首先,创建爱你一个模板基类文件“base.html”

     1 <html>
     2 <head>
     3 {% block head %}
     4 <title>{% block title %}{% endblock %} - My Application</title>
     5 {% endblock %}
     6 </head>
     7 <body>
     8 {% block body %}
     9 {% endblock %}
    10 </body>
    11 </html>

      衍生模板: block 标签定义的元素可以在衍生模板中进行修改,例如,我们定义了名为head itle和body的块。

     1 {% extends "base.html" %}
     2 {% block title %} Indexx {% endblock %}
     3 {% block head %}
     4 {{ super() }}
     5 <style>
     6 </style>
     7 {% endblock %}
     8 {% block body %}
     9 <h1> Hello, World! </h1>
    10 {% endblock %}

      extends指令声明这个模板衍生自base.html。在extends指令后,基模板中的3个块被重新定义,模板引擎会将其插入适当的位置。注意新定义的hea块,在基类模板中其内容不是空的,所以使用super() 函数获取原来的内容。

    以上内容来自于书中摘抄,如有侵权请告知删除。

  • 相关阅读:
    机器学习笔记
    使用pelican创建静态博客
    farbox editor是个好东西
    MamBa项目的插件编写-TikiTorch生成器
    通过rundll32运行C#DLL转储内存
    通过调用Windows本地RPC服务器bypass UAC
    浅谈python反序列化漏洞
    [转载]SQL Server提权系列
    certutil在传输payload中的新奇技巧
    AVIator -- Bypass AV tool
  • 原文地址:https://www.cnblogs.com/PeiFeng-TuNan/p/13179533.html
Copyright © 2011-2022 走看看