除了技术贴编写体验差外,我觉得学习者很多时候很困惑,却不知道自己到底哪里困惑,我们是否可以根据编程知识的特点,给列个通用的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 )