【发布时间】:2014-09-19 01:03:52
【问题描述】:
我想制作一个在 GAE 框架/服务上运行的简单网站。它非常小,我并不真正需要整个强大的 Django 框架,因此我选择了 google 制作的 Webapp2 框架,再加上 Jinja2 模板语言。
我来自一个真正的面向 PHP 和 HTML 的背景,所以我很难适应一个真正的框架的工作方式。我目前最大的疑问来自模板系统和请求处理程序如何协同工作,特别是如果页面的模板有几个“动态”元素。
我将首先解释我以前在 PHP 中所做的事情,以便您更好地理解我想要实现的目标。
假设我想要一个网站:
- 页面标题取决于所访问的页面,例如:“Mysite.com | 控制面板”
- 一个动态菜单栏,可能会根据用户的个人资料或登录状态而变化
- 显然,页面正文完全取决于正在查看的页面
我在 PHP 中的做法因此在这里被压缩成一个简单的例子,index.php:
<?php
/*here use the $_GET or $_POST variable, and the $_SESSION variable
to figure out who's connected, which page is being displayed,
and store those values in global variables, for the
included modules to use */
include('page_header.php'); // renders the whole <head> </head> tag and its content
echo "<body>";
include('views/menu.php'); //generates the menu, displays it
switch($page_name){
case "home":
include('home.php'); //renders the page body for the homepage
break;
case "articles":
include('home.php'); //renders the page body for the blog articles listing
break;
case "guestbook":
include('home.php'); //renders the page body for the guestbook
break;
}
echo "</body>";
每个包含的模块,使用调用它们的脚本中的变量 (index.php) 和 $_POST、$_GET、$_SESSIOn 超全局变量,确定要显示的内容,并将其呈现给 HMTL。这里index.php 也做了一些非常基本的路由,使用 switch 语句。
现在,回到 webapp2 和 jinja2 框架:
我知道,要使用 Jinja 构建网页的模块化方法,您需要使用块结构,并且 extend 那些块。因此,为了构建与前面的 PHP 示例类似的页面,我制作了以下模板 base.html:
<html>
<head>
<link rel="stylesheet" href="/static/css/reset.css">
{% block title %}
{% endblock title %}
</head>
<body>
<div class="menu">
{% block menu %}
{% endblock menu %}
</div>
<div class="body">
{% block content %}
{% endblock content %}
</div>
</body>
</html>
我不明白的是,您将如何构建不同的处理程序,进而生成 Jinja 将用于渲染块的上下文,并避免冗余。 **另外,我可以使用几个不同的模板文件,单独扩展一个块(例如:menu.html,header.html,body_home.html,body_articles.html,...)**
您可以作为回答的基础,this example, from a small example that almost taught me all i needed to know。
感谢您提供的任何帮助,如有任何语法错误,我们深表歉意,英语不是我的母语。
【问题讨论】:
-
我没有在 php 中编程,但是您是否要求将
include一些常见(有些静态)内容放入title和menu中,或者它们是否独立于每个处理程序中?跨度> -
title.php,menu.php可能正在使用一些在执行之前定义的全局变量,是的。为什么要问这个问题? -
您要求构建生成上下文的不同处理程序令人困惑,但您提供的链接正是这样做的,它是
jinja2问题或webapp2问题。 -
两者兼而有之,我只是想知道将这个基本 PHP 架构转换为 webapp2+jinja2 的最佳实践
标签: python google-app-engine jinja2 webapp2