如何使用jinja2

除了技术贴编写体验差外,我觉得学习者很多时候很困惑,却不知道自己到底哪里困惑,我们是否可以根据编程知识的特点,给列个通用的checklist来帮助大家发现自己的问题所在?

比如我就不知道怎么用jinja2,可能我笨,文档我看不懂哈哈,从外网粘贴了篇教程分享给大家。

kagerato.net

A Quickstart Guide to Using the Jinja2 Template Engine

What is Jinja 2 ?

Jinja2 is the second major version of a Python library used to generate documents based on one or more predefined templates.

As to the name, "jinja" is the Japanese word for a Shinto shrine or temple. Temple, template... a clever pun.

API Overview

There are two key objects in the Jinja API: Environment and Template.

Environment objects are used to initialize, store, and configure variables which are significant to template rendering.

Template objects, on the other hand, represent a particular template file and can be used to generate one or more outputs from it.

Beyond these key objects, there is also a secondary set used for reading the template files. These objects are classified as Loaders. The loaders of significance for typical use are FileSystemLoader, PackageLoader, and DictLoader. The three of these read template data from the file system, a Python package, or a Python dictionary, respectively.

Ordinarily, the process one will use to transform a template and its inputs into a rendered output file has four steps.

First, select and construct an appropriate loader object.

Second, create an environment object while specifying that new loader and any other desired options.

Third, use the environment‘s get_template method to read the template file using the loader, and store the resulting template object.

Fourth and finally, process the template by passing any inputs into the render method of the template object.

Leading by Example

Listing 1a: sample Python code

# Load the jinja library‘s namespace into the current module.
import jinja2

# In this case, we will load templates off the filesystem.
# This means we must construct a FileSystemLoader object.
#
# The search path can be used to make finding templates by
#   relative paths much easier.  In this case, we are using
#   absolute paths and thus set it to the filesystem root.
templateLoader = jinja2.FileSystemLoader( searchpath="/" )

# An environment provides the data necessary to read and
#   parse our templates.  We pass in the loader object here.
templateEnv = jinja2.Environment( loader=templateLoader )

# This constant string specifies the template file we will use.
TEMPLATE_FILE = "/home/user/site/example1.jinja"

# Read the template file using the environment object.
# This also constructs our Template object.
template = templateEnv.get_template( TEMPLATE_FILE )

# Specify any input variables to the template as a dictionary.
templateVars = { "title" : "Test Example",
                 "description" : "A simple inquiry of function." }

# Finally, process the template to produce our final text.
outputText = template.render( templateVars )

Listing 1b: sample Jinja template

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8" />

  <title>{{ title }}</title>
  <meta name="description" content="{{ description }}" />
</head>

<body>

<div id="content">
  <p>Why, hello there!</p>
</div>

</body>
</html>

Template Input Variables

Most of what appears above will be familiar to those versed in Python and HTML. The one aspect which is different, and begins to touch on Jinja‘s features, is the template input. It is possible to pass arbitrary strings of text into predefined placeholders in the actual template file itself. Simple variables like this are marked in the template using the {{ variable_name }} syntax.

As one would imagine, the Python code can determine the contents of these variables at runtime. Further, it can perform multiple separate renderings of the same template with different input variable values. There is no arbitrary limit to the number of inputs which may be specified this way, either. These facts allow for a great deal of flexibility.

In some cases, this simple input substitution will be enough for the user‘s needs. Especially for purists who do not want to mix any kind of logic into the template file itself, it makes sense to do all manner of processing in the Python code and then output it to the template through variables like these.

However, there are those who do not agree with that philosophy. They wish to insert presentation logic into the template, and regard processing HTML or other disparate code in the Python as unwise. Jinja is able to accommodate them.

Template Logic

Let us look at how to incorporate some fundamental logic into a template in order to keep the Python code simple.

Listing 2a: Python rendering code

import jinja2

templateLoader = jinja2.FileSystemLoader( searchpath="/" )
templateEnv = jinja2.Environment( loader=templateLoader )

TEMPLATE_FILE = "/home/user/site/example2.jinja"
template = templateEnv.get_template( TEMPLATE_FILE )

# Here we add a new input variable containing a list.
# Its contents will be expanded in the HTML as a unordered list.
FAVORITES = [ "chocolates", "lunar eclipses", "rabbits" ]

templateVars = { "title" : "Test Example",
                 "description" : "A simple inquiry of function.",
                 "favorites" : FAVORITES
               }

outputText = template.render( templateVars )

Listing 2b: Jinja template with a loop

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8" />

  <title>{{ title }}</title>
  <meta name="description" content="{{ description }}" />
</head>

<body>

<div id="content">
  <p>Greetings visitor!  These are a list of my favorite things:</p>

  <ul>
  {% for item in favorites %}
    <li>{{ item }}</li>
  {% endfor %}
  </ul>
</div>

</body>
</html>

Take note of both the for loop added to the template, and the additional list variable in the Python code. In particular, pay attention to the fact that logic expressions use a {% ... %} syntax. Using the variable expansion syntax would be a template bug. More implications are discussed below.

Jinja supports a subset of control structures that are very similar to Python. The critical two are if and for. Their syntax is similar to Python, only differing in that no colon is required at the end of the statement and that termination of the block is done using an endif orendfor instead of by whitespace. Most user needs for presentational logic can be met with just these two elements.

In the above example, a list of strings is iterated over in a very similar manner to how it would be done in Python. A temporary variable, item, will store the current value of an element of the list for each iteration of the loop. In this case, we merely print the item value inside a list item tag.

Of course, one could do the same effective work in the Python code instead. This would involve a series of selective string concatenations with HTML inline. Then the preprocessed output would be written via a template variable. This works, but has a significant issue with structural clarity. It may also be difficult to maintain an exact formatting of whitespace, especially in a complicated template.

时间: 2024-12-12 21:53:00

如何使用jinja2的相关文章

[Jinja2]本地加载html模板

import os from jinja2 import Environment, FileSystemLoader env = Environment(loader=FileSystemLoader('.')) template = env.get_template('index.html') print(template.render()) 然而Django也能做到 只是貌似需要配置或者创建完整的Django项目app才行

Django1.10配置Jinja2模板

1.安装Jinja2模块: pip install jinja2 2.配置settings: TEMPLATES = [     {         'BACKEND': 'django.template.backends.jinja2.Jinja2',         'DIRS': [os.path.join(BASE_DIR, 'templates')],         'APP_DIRS': True,         'OPTIONS': {             'environ

Python自定义web框架、Jinja2

WSGI(Web Server Gateway Interface)是一种规范,它定义了使用python编写的web app与web server之间接口格式,实现web app与web server间的解耦. python标准库提供的独立WSGI服务器称为wsgiref. 标准Web框架 #!/usr/bin/env python #coding:utf-8 from wsgiref.simple_server import make_server def RunServer(environ,

自定义jinja2 过滤器

今天,我们要讲的是自定义jinja2 过滤器这个知识点,因为官方文档对此一代而过,讲得不够清楚,所以我们专门拿出来讲一下. 例子 例子写了两个自定义过滤器,一个是转换字典到字符串的过滤器,一个是返回当前参数的类型的过滤器. 源代码: https://github.com/lewis617/jinja2-filter filter是个函数 filter是个函数,跟angular的过滤器几乎一模一样.参数就是管道(pipe)前面那个变量.比如   123|myfilter,123就是myFilter

Ansible用于网络设备管理 part 2 对Jinja2 YAML 和 module的理解

虽然很不想用“应该”这个词,但是还是写上了,的确我自己目前就是这么理解的. 那么这个理解就是,Ansible的一个key point 就是总的一个playbook是去依赖很多元素的,就像一开始那个图里画的,如下图 这里面就涉及到它下挂的不管是yml文件还是Jinja2文件,这些文件的内部一定是和Ansible这个东西相紧密关联的,我之前之所以不那么理解就是在于这一点没有弄清楚,再说明白一点就是下面的内容 看到task:下面的东西了么?name, yum, service,还有在Jinja2文件(

Jinja2 简明使用手册

@Jinja2 简明使用手册(转载) 介绍 Jinja是基于python的模板引擎,功能比较类似于于PHP的smarty,J2ee的Freemarker和velocity. 运行需求 Jinja2需要Python2.4以上的版本. 安装 按照Jinja有多种方式,你可以根据需要选择不同的按照方式. 使用easy_install安装 使用easy_install 或pip: #sudo easy_install Jinja2 #sudo pip install Jinja2 这两个工具可以自动从网

JinJa2 源代码分析

学习方式 从 JinJa 2.0 版本开始学习,之前的版本里有不少编译错误,测试用例也不全,可以先看比较完整的 2.0 版本, 弄清楚主要思路,再看之前的提交过程. JinJa 2.0 概要 JinJa2 简介 JinJa2 是一个 Python 实现的模板引擎,模板引擎的作用就是把一个 HTML 模板,以及一些环境变量,生成 HTML 页面.模板引擎的使用, 可以使我们在 Web 开发中,将不变的部分(HTML 模板) 与变化的部分(环境变量)分开.HTML 模板中不仅支持对变量值进行替换,还

Flask Web Development - Flask 模板1 - 模板机制&Jinja2引擎

节选自PartI Chapter3,这个chapter主要讲模板工作原理,这里讲的就是Jinja2这个模板,另外还提到了Flask-Bootstrap及Flask-Moment两个插件,前者对Flask使用Bootstrap做了些封装,后者对moment.js做了些封装.内容较多,估计分开搞. 模板存在的意义 可维护性高的代码是结构良好且整洁的. 当用户在网站注册一个账户时,他在表单里填入邮箱跟密码,并点击提交按钮.在server端就收到一个包含这些数据的request,再由Flask分发到相应

在windows上如何安装python web引擎jinja2

首先要把你的Python文件夹加到环境变量里头去.假设你的Python文件夹位于C:\Python34,那么你需要打开CMD并输入: SETX PATH "%path%;C:\Python34;C:\Python34\Scripts" 然后把 https://bootstrap.pypa.io/get-pip.py 这个文件下载下来,并在CMD中运行: python get-pip.py 这样你的pip管理工具就安装好了,下面你就只要按照如图所示: pip install Jinja2

[Webpy]在webpy中使用jinja2模板

webpy的模板感觉写小的网页还可以,但是如果要是写比较多的html标签就会显得非常乱,于是决定使用jinja2,这个模板类似django的模板,而且跟其他pythonweb框架的兼容性也比较好. 在项目目录下新建一个settings文件 #-*- coding: utf-8 -*- __author__ = 'orangleliu' ''' settings of the project ''' import os import web from web.contrib.template im