我一直在寻找有关如何编写Jinja代码的大量信息,并且有2个.py文件page1.py
和page2.py
引用.jinja
个文件templates
目录。当我运行python page1.py
时,我准确地获得了我想要的网页。事实上,当我运行python page1.py > page1.html
然后导航到myWebpage/page1.html
时,它就能完美运行。
但是,我想知道,一旦我将myWebpage/page1.html
输入浏览器,jinja应该(或可以)自动运行。问题是,一旦后端的参数发生变化,我就会使用Jinja自动更新页面。我是否需要使用cron
运行此python代码,或者是否应该在用户刷新网页时生成新的.html
代码?
以下是我的python和jinja页面的内容:
(1)/var/www/html/page1.py
的内容#!/usr/bin/env python
### taken from http://kagerato.net/articles/software/libraries/jinja-quickstart.html
# 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="/usage_statistics/webfront" )
# 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 = "templates/page1.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 )
print outputText
(2)/var/www/html/templates/page1.jinja
的内容<!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>
(3)/var/www/html/page2.py
的内容#!/usr/bin/env python
import jinja2
templateLoader = jinja2.FileSystemLoader( searchpath="/usage_statistics/webfront" )
env = jinja2.Environment( loader=templateLoader )
TEMPLATE_FILE = "templates/page2.jinja"
template = env.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 )
#template.render( templateVars )
print template.render( templateVars )
(4)page2.jinja的内容
<!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>