0

如何根据 base.html 的 url 做出特定的操作?

我在 base.html 中有两个 if 子句作为上下文语句。如果 GET 中有代数,则应显示给定的上下文。

我的 url.conf

from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'^algebra/$', 'algebra'),
    (r'^mathematics/$', 'mathematics'),

)

我的伪代码中的 base.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
  <body>
              {% if algebra %}                                    
                  <div>... -- do this -- </div> 
              {% endif %}

              {% if math %}
                  <div>... -- do this -- </div>
              {% endif %}
4

2 回答 2

2

您不显示视图功能,但这是一个简单的结构:

def algebra(request):
    return common_view(request, algebra=True)

def math(request):
    return common_view(request, math=True)

def common_view(request, math=False, algebra=False):
    ctx = Context()
    ctx['algebra'] = algebra
    ctx['math'] = math
    # blah blah, all the other stuff you need in the view...
    return render_to_response("base.html", ctx)

(我可能有一些错别字,它不在我的脑海中)。

于 2010-01-05T01:13:41.167 回答
1

Ned 的基于变量值的方法的替代方法是使用两个不同的模板来扩展一个通用的基本模板。例如

在模板/base.html 中:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
  <body>
      {% block main_body %}                                    
      {% endblock main_body %}                                    
       etc., etc.

然后让你的代数视图使用模板/algebra.html:

{% extends "base.html" %}

{% block main_body %}
  do algebra stuff here
{% end block main_body %}

并为之或其他做类似的math事情。每种方法都有优点和缺点。选择最适合您问题的那个。

更新:"algebra.html"作为第一个参数传递给render_to_response(). 它的扩展 "base.html"在于它使用了所有它,除了它显式替换的块。有关其工作原理的说明,请参阅模板继承。模板继承是一个非常强大的概念,可以在大量页面中实现一致的外观和感觉,这些页面的主体不同,但共享部分或全部菜单等您可以进行多级模板继承,这非常好用于管理具有与“主要外观”有显着差异但希望尽可能多地共享 HTML/CSS 的子部分的站点。

这是模板世界中DRY(不要重复自己)的关键原则。

于 2010-01-05T01:53:25.033 回答