我有五个页面具有相同的页面布局和结构,但有一些不同的颜色、文本等,因此这是一个理想的模板环境。我决定使用 Jinja2 和 Flask。我已通读文档和一些在线教程,其中解释了很多有关如何使用页面上的模板执行的操作,但没有太多有关如何将变量发送到页面的信息。
- 您在哪里存储特定于页面的变量?
- 代码如何知道已请求哪个页面以及要加载哪些变量?
I've got five pages with the same page layout and structure, but some different colors, text, etc, so this is an ideal environment for templating. I've decided to use Jinja2 and probably flask. I've read through the documentation, and some tutorials online, which explain lots about what you can do with templates on a page but not much about how to send variables to the page.
- Where do you store the page-specific variables?
- How does the code know which page has been requested and which variables to load?
发布评论
评论(2)
以下是基本用法:
首先创建一个模板
然后通过变量来渲染它
通常您会希望从文件而不是代码中加载模板。这更加高效和优化,并允许模板继承:
它将在
yourapplication
Python 包的templates
文件夹内查找模板,安装在 Python 路径中。您也可以使用其他加载器从特定文件系统或其他位置加载。然后你可以加载一个模板:
当使用 Flask 时,它已经为你配置好了,所以你只需使用 Flask 的 render_template 函数,它就会寻找你的模板的子文件夹应用程序:
请注意传递给
render_template
的模板变量(也称为 context)Jinja 有漂亮的 良好的文档。请阅读它。请随时提出进一步的问题。
Here's the basic usage:
First create a template
Then render it passing the variables
Usually you will want to load templates from files instead of code. That's more efficient and optimized, and allows template inheritance:
That will look for templates inside the
templates
folder of theyourapplication
Python package, as installed in the Python path. You could use other loaders to load from a specific filesystem or other places too.Then you can load a template:
When using Flask it is all configured for you, so you can just use Flask's
render_template
function and it will already look for atemplates
subfolder of your application:Note the template variable (also known as context) being passed to
render_template
Jinja has pretty good documentation. Please read it. Feel free to ask further questions.
编辑:我在互联网上搜索答案,发现了一些可以提供帮助的文章(很确定它们对我有帮助)
http://dbanck.de/2009/01/13/using-jinja2-with-django/
http://www.hindsightlabs.com/blog/2010/03 /15/jinja2-and-django-4ever/(已死)http:// /djangosnippets.org/snippets/1061/
Edit: I've googled the interweb in search for an answer and I've found some articles that could help (pretty sure they've helped me)
http://dbanck.de/2009/01/13/using-jinja2-with-django/
http://www.hindsightlabs.com/blog/2010/03/15/jinja2-and-django-4ever/(dead)http://djangosnippets.org/snippets/1061/