Django 基礎05篇 上下文管理和前端程式碼複用
阿新 • • 發佈:2020-12-05
一、上下文管理器
在views中重複使用的程式碼,可以通過上下文管理器(在setting.py檔案中的TEMPLATES中配置)中實現,減少程式碼冗餘
上下文管理器的處理流程如下:
1.先走完views裡面的程式碼,將結果返回給前端
2.然後再將上下文的結果返回給前端
3.上下文只有在返回的是html的時候,才會走上下文處理器
當views和上下文處理器中都定義了的變數值,那麼HTML頁面中以views中定義的為準。
1.1上下文context_process.py程式碼
from . import models def category_process(request): # 先走到views,然後在走到setting中的TEMPLATES上下文管理器中categories = models.Category.objects.all() return {'title': 'XXX部落格', 'categories': categories}
1.2setting.py檔案中的配置
TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True,'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'user.context_process.category_process' ], }, }, ] # 前後端不分離時用到
二、前端公共程式碼複用
前端很多程式碼是在不同頁面中都是一樣的,每個都去修改一遍,工作量太大,並且程式碼重複,所以引入了公共程式碼複用。
1.先建立複用程式碼base.html,如果這一塊程式碼不是公共的,則預留程式碼塊
{% blockbody%}
//預留程式碼塊,body是唯一
{% endblock %}
<!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="referrer" content="origin"> <!-- TDK and ICO --> <title>Tend to Code_一個使用django和bootstrap搭建的個人部落格_TendCode</title> <meta name="description" content="TendCode是一個Django搭建的部落格,本網站後端使用Django框架搭建,前端使用Bootstrap框架,主要分享博主在Python以及其他程式語言的學習心得。"> <meta name="keywords" content="Python自學,Python爬蟲,Django部落格,Python web開發,個人部落格"> <!--站長驗證--> <link rel="shortcut icon" href="/static/blog/img/favicon.ico" type="image/x-icon"/> <!-- Bootstrap and font-awesome CSS --> <link href="https://cdn.bootcss.com/twitter-bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"> <link href="https://cdn.bootcss.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"> <script src="/static/js/headroom.min.js"></script> <!-- blog CSS --> <link href="/static/css/base.css" rel="stylesheet"> <!--根據cookies判斷是否啟用暗色主題--> {% block css %} {% endblock %} </head> <body> <!--導航開始--> <nav class="navbar navbar-expand-md bg-white fixed-top blog-navbar py-md-0"> <a class="navbar-brand d-md-none d-lg-block" id="site-logo-name" href="/"> <strong class="px-2">{{ title }}</strong> </a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav ml-auto"> <li class="nav-item mr-2"> <a class="nav-link py-md-3 active" href="/"><i class="fa fa-home mr-1"></i>首頁<span class="sr-only">(current)</span></a> </li> <li class="nav-item mr-2"> <a class="nav-link py-md-3 " href="./archive.html"><i class="fa fa-sitemap mr-1"></i>歸檔</a> </li> <form class="nav-item navbar-form mr-2 py-md-2" role="search" method="get" id="searchform" action="/search/"> <div class="input-group"> <input type="search" name="q" class="form-control rounded-0" placeholder="站內搜尋" autocomplete="off" required=True> <div class="input-group-btn"> <button class="btn btn-info rounded-0" type="submit"><i class="fa fa-search"></i></button> </div> </div><!-- /input-group --> </form> </ul> </div> </nav> <!--導航結束--> <!--訊息塊--> <!--回到頂部按鈕--> <div class="text-center" id="to-top"> <i class="fa fa-chevron-up" id="btn-top" title="回到頂部"></i> </div> <!--主要內容塊--> <main> <div class="container"> <div class="row"> {% block body %} {% endblock %} <div class="col-lg-4"> <!--個人空間--> <div class="card border-0 rounded-0 px-3 mb-2 mb-md-3 d-none d-lg-block" id="home-card"> <div class="card-header bg-white px-0"> <strong><i class="fa fa-paper-plane mr-2 f-17"></i>個人空間</strong> </div> <div class="card-body px-0 pt-3 pb-1"> <div class="row text-center"> <div class="col"> <a href="https://github.com/Hopetree" target="_blank" title="進入博主的Github檢視部落格原始碼"> <img style="max-width:40px" alt="博主的github" src="https://tendcode.com/static/blog/img/github.png"> <p class="mt-2">Github</p> </a> </div> <div class="col"> <a href="/timeline/" target="_blank" title="檢視網站建站歷程"> <img style="max-width:40px" alt="網站的建站歷程" src="https://tendcode.com/static/blog/img/blog.png"> <p class="mt-2">Timeline</p> </a> </div> <div class="col"> <a href="/timeline/" target="_blank" title="檢視網站建站歷程"> <img style="max-width:40px" alt="網站的建站歷程" src="https://tendcode.com/static/blog/img/blog.png"> <p class="mt-2">Timeline</p> </a> </div> </div> </div> </div> <!--文章分類--> <div class="card border-0 rounded-0 px-3 mb-2 mb-md-3" id="category-card"> <div class="card-header bg-white px-0"> <strong><i class="fa fa-book mr-2 f-17"></i>文章分類</strong> </div> <ul class="list-group list-group-flush f-16"> {% for category in categories %} <li class="list-group-item d-flex justify-content-between align-items-center pr-2 py-2"> <a class="category-item" href="/category/{{ category.id }}" title="檢視【CI/CD】分類下所有文章">{{ category.name }}</a> <span class="badge text-center" title="當前分類下有{{ category.article_set.count }}篇文章">{{ category.article_set.count }}</span> </li> {% endfor %} </ul> </div> <!--標籤雲--> <div class="card border-0 rounded-0 px-3 mb-2 mb-md-3" id="tag-card"> <div class="card-header bg-white px-0"> <strong><i class="fa fa-tags mr-2 f-17"></i>標 籤 雲</strong> </div> <div class="card-body px-0 py-3"> <div class="tag-cloud"> {% for tag in tag_list %} <a href="/tag/{{ tag }}/" class="tags f-16" id="tag-1" title="【{{ tag }}】標籤下有3篇文章">{{ tag }}</a> {% endfor %} </div> </div> </div> <!--友鏈--> <div class="d-none d-lg-block"> <div class="card border-0 rounded-0 px-3 mb-2 mb-md-3" id="friends-card"> <div class="card-header bg-white px-0"> <strong><i class="fa fa-link mr-2 f-17"></i>友情連結</strong> </div> <div class="card-body px-0 py-3"> <div class="tool-list"> <div class="w-50 float-left text-center mb-2"> <div class="mx-2"> <a href="https://github.com/Hopetree/izone" title="izone 部落格專案的原始碼" target="_blank"> 部落格原始碼</a> </div> </div> <div class="w-50 float-left text-center mb-2"> <div class="mx-2"> <a href="https://frostming.com" title="一個基於 Flask 開發的部落格" target="_blank"> Frost's Blog</a> </div> </div> <div class="w-50 float-left text-center mb-2"> <div class="mx-2"> <a href="https://zmrenwu.com" title="Django 部落格教程分享者" target="_blank"> 追夢人物</a> </div> </div> <div class="w-50 float-left text-center mb-2"> <div class="mx-2"> <a href="https://www.dusaiphoto.com/" title="Django 搭建的部落格,分享部落格教程" target="_blank"> 杜賽的個人網站</a> </div> </div> <div class="w-50 float-left text-center mb-2"> <div class="mx-2"> <a href="https://www.jerrycoding.com/" title="Jerry 的個人部落格" target="_blank"> Jerry Coding</a> </div> </div> <div class="w-50 float-left text-center mb-2"> <div class="mx-2"> <a href="https://boywithacoin.cn/" title="Stray_Camel的個人技術部落格" target="_blank"> Stray_Camel</a> </div> </div> </div> </div> </div> </div> </div> </div> </div> </main> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script> <!--js cookie 外掛--> <script src="/static/js/js.cookie.min.js?v=20191123.12"></script> <script src="https://cdn.bootcss.com/popper.js/1.14.7/umd/popper.min.js"></script> <script src="https://cdn.bootcss.com/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script> <script> $(function () { var myElement = document.querySelector(".blog-navbar"); var headroom = new Headroom(myElement); headroom.init() }); </script> <script src="/static/js/base.js?v=20191123.0909890"></script> <footer class="container-fluid mt-4 py-0"> <div class="card-body text-center px-0 f-14"> <p class="card-text mb-1">Copyright © <span id="year-info"></span> Powered by Django. </p> </div> </footer> </body> </html>base.html
2.在index.html中要複用base.html程式碼
先繼承base.html
{% extends 'base.html' %}
在加入不復用的程式碼
{% blockbody%}
{% endblock %}
{% extends 'base.html' %} {% block body %} <div class="col-lg-8"> <div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel"> <ol class="carousel-indicators"> <li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li> <li data-target="#carouselExampleIndicators" data-slide-to="1"></li> <li data-target="#carouselExampleIndicators" data-slide-to="2"></li> <li data-target="#carouselExampleIndicators" data-slide-to="3"></li> </ol> <div class="carousel-inner"> <div class="carousel-item active"> <a href="./detail.html"> <img class="w-100" src="https://tendcode.com/cdn/article/180415/jiandan.png" alt="容器化部署部落格(3)—— 5分鐘完成專案遷移"> </a> </div> <div class="carousel-item"> <a href="/article/set-up-django-with-nginx-and-gunicorn/"> <img class="w-100" src="https://tendcode.com/cdn/article/180415/jiandan.png" alt="在 Linux 伺服器上使用 Nginx + Gunicorn 部署 Django 專案的正確姿勢"> </a> </div> <div class="carousel-item"> <a href="/article/virtualenv-for-python/"> <img class="w-100" src="https://tendcode.com/cdn/article/180415/jiandan.png" alt="Python虛擬環境Virtualenv分別在Windows和Linux上的安裝和使用"> </a> </div> <div class="carousel-item"> <a href="/article/jiandan-meizi-spider/"> <img class="w-100" src="https://tendcode.com/cdn/article/180415/jiandan.png" alt="煎蛋網妹子圖爬蟲"> </a> </div> </div> <a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> <div class="text-secondary font-weight-bold py-2 f-15 choice"> <a class="pb-2 active" href="/"> <i class="fa fa-bars mr-1"></i>時間排序</a> </div> <div class="summary-list"> {% for article in articles %} <div class="media mb-1 mb-sm-2 p-2 p-lg-3"> <div class="align-self-center mr-2 mr-lg-3 w-25 modal-open"> <a href="/article/{{ article.id }}" target="_blank"> <img class="w-100 article-img" src="https://tendcode.com/cdn/article/191029/python_shell.png" alt="Python 模板渲染庫 yaml 和 jinja2 的實戰經驗分享"> </a> </div> <div class="media-body"> <div class="text-muted mb-2 f-12"> <img class="avatar" src="https://tendcode.com/media/avatar/2019/07/27/91ef76c6a7efce1b99717f97a851f3deb48f6510.png" alt="Hopetree"> <span>Hopetree</span> <span><i class="fa fa-calendar-times-o ml-2 mr-1"></i>{{ article.create_time |date:"Y-m-d H:i:s" }}</span> <!-- --> </div> <h2 class="mt-0 font-weight-bold text-info f-17"> <a href="/article/{{ article.id }}" target="_blank">{{ article.title }}</a> </h2> <p class="d-none d-sm-block mb-2 f-15">{{ article.content | truncatechars:50 }}</p> <div class="text-muted mb-0 f-12"> <a class="cate" href="/category/{{ article.category.id }}" title="檢視當前分類下更多文章"> <i class="fa fa-book mr-1"></i>{{ article.category.name }}</a> <span><i class="fa fa-eye ml-2 mr-1"></i>{{ article.read_count }}</span> <a href="/article/yaml_and_jinja2/#comment-block" target="_blank" title="檢視文章評論"> <i class="fa fa-comments ml-2 mr-1"></i>8</a> </div> </div> </div> {% endfor %} </div> <div class="text-center mt-2 mt-sm-1 mt-md-0 mb-3 f-16"> {% if articles.has_previous %} <a class="text-success" href="?page={{ articles.previous_page_number }}">上一頁</a> {% else %} <span class="text-secondary" title="當前頁已經是首頁">上一頁</span> {% endif %} <span class="mx-2">第 {{ articles.number }} / {{ articles.paginator.num_pages }} 頁</span> {% if articles.has_next %} <a class="text-success" href="?page={{ articles.next_page_number }}">下一頁</a> {% else %} <span class="text-secondary" title="當前頁已經是尾頁">下一頁</span> {% endif %} </div> </div> {% endblock %}index.html