接着上篇,我们继续来完成项目。我们知道项目中的前端页面会有很多重复性的代码,为了方便后期的维护,我们使用模板继承的方法来抽象父模板文件。
1.抽象父模板文件
首先抽离出所有页面的基类页面文件、有无购物车字样基类页面文件、详情与列表页基类页面以及用户中心涉及到的3个基类文件;
(1)基类页面文件 base.html
{# 商品首页、商品详情页、商品列表页、注册页面、登录页面 #}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="zh">
{% load staticfiles %}
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
{# 网页标题 #}
<title>{% block title %}极致果蔬商城-水果商城{% endblock title %}</title>
<link rel="stylesheet" type="text/css" href="{% static 'css/reset.css' %}">
<link rel="stylesheet" type="text/css" href="{% static 'css/main.css' %}">
{# 网页顶部引入文件块 #}
{% block topfile %}{% endblock topfile %}
</head>
<body>
{# 网页顶部-欢迎信息 #}
{% block header_welcome %}
<div class="header_con">
<div class="header">
<div class="welcome fl">欢迎来到极致果蔬!</div>
<div class="fr">
{% if user.is_authenticated %}
<div class="login_info fl">
欢迎您:<em>{
{ user.username }}</em>
<a href="{% url 'logout' %}">退出</a>
</div>
{% else %}
<div class="login_btn fl">
<a href="{% url 'login' %}">登录</a>
<span> | </span>
<a href="{% url 'register' %}">注册</a>
</div>
{% endif %}
<div class="user_link fl">
<span> | </span>
<a href="{% url 'userinfo' %}">用户中心</a>
<span> | </span>
<a href="cart.html">我的购物车</a>
<span> | </span>
<a href="user_center_order.html">我的订单</a>
</div>
</div>
</div>
</div>
{% endblock header_welcome %}
{# 网页搜索框 #}
{% block search_bar %}
<div class="search_bar clearfix">
<a href="{% url 'index' %}" class="logo fl"><img src="{% static 'images/logo.png' %}"></a>
<div class="guest_cart fr">
<a href="#" class="cart_name fl">我的购物车</a>
<div class="goods_count fl" id="show_count">1</div>
</div>
<div class="search_con fr">
<input type="text" class="input_text fl" name="" placeholder="搜索商品">
<input type="button" class="input_btn fr" name="" value="搜索">
</div>
</div>
{% endblock search_bar %}
{# 网站主体内容 #}
{% block body_content %}{% endblock body_content %}
<div class="footer no-mp">
<div class="foot_link">
<a href="#">关于我们</a>
<span> | </span>
<a href="#">联系我们</a>
<span> | </span>
<a href="#">招聘人才</a>
<span> | </span>
<a href="#">友情链接</a>
</div>
<p>CopyRight @ 2019 深圳极致果蔬有限公司 All Rights Reserved</p>
<p>电话:0321-#####666 粤ICP 备#########6号</p>
</div>
{# 网页底部html元素块 -如浏览信息 #}
{% block bottom %}{% endblock bottom %}
{# 网页底部引入文件块(有些js的文件较大,放在后面加载,页面不至于停在前面出不来,导致用户跳转) #}
{% block bottomfiles %}{% endblock bottomfiles %}
</body>
</html>
(2)有无购物车字样基类页面文件 base_no_cart.html
{# 购物车、订单页面、用户中心 #}
{% extends "base.html" %}
{% block search_bar %}
{% load staticfiles %}
<div class="search_bar clearfix">
<a href="{% url 'index' %}" class="logo fl"><img src="{% static 'images/logo.png' %}"></a>
<div class="sub_page_name fl">| {% block pagetitle