Template初探
到目前為止我們只是簡(jiǎn)單的將后端數(shù)據(jù)顯示到頁面上, 沒有涉及到HTML代碼, 而優(yōu)雅的網(wǎng)站總算通過CSS+HTML, 甚至還有強(qiáng)大的JS的支持.
在這個(gè)教程中要打造一個(gè)Blog, 所以我們?cè)O(shè)置一個(gè)Blog界面, 原本打算使用Bootstrap作為前段的工具, 不過經(jīng)過@游逸的建議, 使用了更加輕量級(jí)的Pure, 同樣是響應(yīng)式頁面設(shè)置, 這也將是未來的主流吧..
在my_blog下添加文件名, 文件夾名為templates
mkdir templates
#看到當(dāng)前文件構(gòu)成
my_blog
├── article
│ ├── __init__.py
│ ├── __pycache__
│ │ ├── __init__.cpython-34.pyc
│ │ ├── admin.cpython-34.pyc
│ │ ├── models.cpython-34.pyc
│ │ └── views.cpython-34.pyc
│ ├── admin.py
│ ├── migrations
│ │ ├── 0001_initial.py
│ │ ├── __init__.py
│ │ └── __pycache__
│ │ ├── 0001_initial.cpython-34.pyc
│ │ └── __init__.cpython-34.pyc
│ ├── models.py
│ ├── tests.py
│ └── views.py
├── db.sqlite3
├── manage.py
├── my_blog
│ ├── __init__.py
│ ├── __pycache__
│ │ ├── __init__.cpython-34.pyc
│ │ ├── settings.cpython-34.pyc
│ │ ├── urls.cpython-34.pyc
│ │ └── wsgi.cpython-34.pyc
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
└── templates
在my_blog/my_blog/setting.py下設(shè)置templates的位置
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'templates').replace('\\', '/'),
)
1.7/1.8版本Django已經(jīng)修改的template添加形式
#嘗試這種寫法
TEMPLATE_PATH = os.path.join(BASE_DIR, 'templates')
TEMPLATE_DIRS = (
TEMPLATE_PATH,
)
第一個(gè)template
templates/test.html簡(jiǎn)單第一個(gè) template html文件
<!--在test.html文件夾下添加-->
<!DOCTYPE html>
<html>
<head>
<title>Just test template</title>
<style>
body {
background-color: red;
}
em {
color: LightSeaGreen;
}
</style>
</head>
<body>
<h1>Hello World!</h1>
<strong>{{ current_time }}</strong>
</body>
</html>
其中{{ current_time }}是Django Template中變量的表示方式
意思是告知項(xiàng)目templates文件夾在項(xiàng)目根目錄下
在article/view.py中添加一個(gè)函數(shù)邏輯
from django.shortcuts import render
from django.http import HttpResponse
from article.models import Article
from datetime import datetime
# Create your views here.
def home(request):
return HttpResponse("Hello World, Django")
def detail(request, my_args):
post = Article.objects.all()[int(my_args)]
str = ("title = %s, category = %s, date_time = %s, content = %s"
% (post.title, post.category, post.date_time, post.content))
return HttpResponse(str)
def test(request) :
return render(request, 'test.html', {'current_time': datetime.now()})
render()函數(shù)中第一個(gè)參數(shù)是request 對(duì)象, 第二個(gè)參數(shù)是一個(gè)模板名稱撬槽,第三個(gè)是一個(gè)字典類型的可選參數(shù). 它將返回一個(gè)包含有給定模板根據(jù)給定的上下文渲染結(jié)果的 HttpResponse對(duì)象度液。
然后設(shè)置對(duì)應(yīng)的url在my_blog/urls.py下
url(r'^test/$', 'article.views.test'),
重新啟動(dòng)服務(wù)器python manage.py runserver, 然后在瀏覽器中輸入http://127.0.0.1:8000/test/, 可以看到
正式編寫template
在template文件夾下增加base.html, 并在其中增加如下代碼
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="A layout example that shows off a blog page with a list of posts.">
<title>Andrew Liu Blog</title>
<link rel="stylesheet" >
<link rel="stylesheet" >
<link rel="stylesheet" >
</head>
<body>
<div id="layout" class="pure-g">
<div class="sidebar pure-u-1 pure-u-md-1-4">
<div class="header">
<h1 class="brand-title">Andrew Liu Blog</h1>
<h2 class="brand-tagline">雪憶 - Snow Memory</h2>
<nav class="nav">
<ul class="nav-list">
<li class="nav-item">
<a class="pure-button" >Github</a>
</li>
<li class="nav-item">
<a class="pure-button" >Weibo</a>
</li>
</ul>
</nav>
</div>
</div>
<div class="content pure-u-1 pure-u-md-3-4">
<div>
{% block content %}
{% endblock %}
<div class="footer">
<div class="pure-menu pure-menu-horizontal pure-menu-open">
<ul>
<li><a >About Me</a></li>
<li><a >Twitter</a></li>
<li><a >GitHub</a></li>
</ul>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
上面這段html編寫的頁面是一個(gè)模板, 其中{% block content %} {% endblock %}字段用來被其他繼承這個(gè)基類模板進(jìn)行重寫
我們繼續(xù)在templates文件夾下添加home.html文件
{% extends "base.html" %}
{% block content %}
<div class="posts">
{% for post in post_list %}
<section class="post">
<header class="post-header">
<h2 class="post-title">{{ post.title }}</h2>
<p class="post-meta">
Time: <a class="post-author" href="#">{{ post.date_time }}</a> <a class="post-category post-category-js" href="#">{{ post.category }}</a>
</p>
</header>
<div class="post-description">
<p>
{{ post.content }}
</p>
</div>
</section>
{% endfor %}
</div><!-- /.blog-post -->
{% endblock %}
其中
- {% for <element> in <list> %}與{% endfor %}成對(duì)存在, 這是template中提供的for循環(huán)tag
- {% if <elemtnt> %} {% else %} {% endif %}是template中提供的if語句tag
- template中還提供了一些過濾器
然后修改my_blog/article/view.py, 并刪除test.html
# -*- coding: utf-8 -*-
from django.shortcuts import render
from django.http import HttpResponse
from article.models import Article
from datetime import datetime
# Create your views here.
def home(request):
post_list = Article.objects.all() #獲取全部的Article對(duì)象
return render(request, 'home.html', {'post_list' : post_list})
修改my_blog/my_blog/urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'my_blog.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^$', 'article.views.home'),
)
現(xiàn)在重新打開http://127.0.0.1:8000/, 發(fā)現(xiàn)Blog的整理框架已經(jīng)基本完成, 到現(xiàn)在我們已經(jīng)了解了一些Django的基本知識(shí), 搭建了簡(jiǎn)單地Blog框架, 剩下的就是給Blog添加功能
查看當(dāng)前整個(gè)程序的目錄結(jié)構(gòu)
my_blog
├── article
│ ├── __init__.py
│ ├── __pycache__
│ │ ├── __init__.cpython-34.pyc
│ │ ├── admin.cpython-34.pyc
│ │ ├── models.cpython-34.pyc
│ │ └── views.cpython-34.pyc
│ ├── admin.py
│ ├── migrations
│ │ ├── 0001_initial.py
│ │ ├── __init__.py
│ │ └── __pycache__
│ │ ├── 0001_initial.cpython-34.pyc
│ │ └── __init__.cpython-34.pyc
│ ├── models.py
│ ├── tests.py
│ └── views.py
├── db.sqlite3
├── manage.py
├── my_blog
│ ├── __init__.py
│ ├── __pycache__
│ │ ├── __init__.cpython-34.pyc
│ │ ├── settings.cpython-34.pyc
│ │ ├── urls.cpython-34.pyc
│ │ └── wsgi.cpython-34.pyc
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
└── templates
├── base.html
└── home.html
將代碼上傳到Github
在github中新建倉庫my_blog_tutorial, 填寫簡(jiǎn)單的描述
#查看當(dāng)前目錄位置
$ pwd
/Users/andrew_liu/Python/Django/my_blog
#在項(xiàng)目的根目錄下初始化git
git init
Initialized empty Git repository in/Users/andrew_liu/Python/Django/my_blog/.git/
#添加遠(yuǎn)程github
$ git remote add blog git@github.com:Andrew-liu/my_blog_tutorial.git
在根目錄下增加`.gitignore'和'LICENSE'和'README.md'文件
#添加所有文件
$ git add .
#查看當(dāng)前狀態(tài)
$ git status
#commit操作
$ git commit -m "django tutorial init"
#上傳github
$ git push -u blog master
Counting objects: 23, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (22/22), done.
Writing objects: 100% (23/23), 19.56 KiB | 0 bytes/s, done.
Total 23 (delta 1), reused 0 (delta 0)
To git@github.com:Andrew-liu/my_blog_tutorial.git
* [new branch] master -> master
Branch master set up to track remote branch master from blog.