iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 5
0
Modern Web

使用 Django 開發網頁系統系列 第 5

[Day 05] Templates 範本

今天來聊聊 Templates(範本)

templates 是在 MVC 中的 View
是處理前端,顯示頁面

前端 常用的是語言 HTML 5, CSS 3, JavaScript

之前在 views.py return 的是 HttpResponse('')
改成 return 一個頁面
在app 目錄下新建一個 templates 資料夾
再一個 app_name 資料夾 ,就可以新增 xx.html 了

專案目錄

shop/
----venv/
----shop/
-------manage.py
-------shop/
-----------__init__.py
-----------settings.py
-----------wsgi.py
-----------urls.py
-------main/
-----------__init__.py
-----------views.py
-----------...
-----------templates/
---------------main/
-------------------main.html

views.py

def main(request):
    return render(request, 'main/main.html')

main.html 基本html格式

<!doctype html>
<html>
<head></head>
<body>
Hello world 
</body>
</html>

templates 其他常用功能
傳遞範本變數
可以從views.py 傳變數到前端顯示
放第三個參數,是使用 dict{} 型態
key: 是變數
value: 值
views.py

def main(request):
    return render(request, 'main/main.html', {'message':'hello'})

main.html

…
<body>
Hello wrold
{{ message }}
</body>
...

templates 也可以寫 邏輯判斷,for loop
使用到{% %} 這行裡面的變數就不需 {{ }},如果是字串就需要加 ''
if

{% if variable == 'in' %}
     someting...
{% else %}
    someting...
{% end if %}

forloop

{% for item in items %}
    {{ item }}
{% endfor %}

官網 template tag 介紹
https://docs.djangoproject.com/en/2.0/ref/templates/builtins/

今天就先寫到這裡 之後會用到 extends include 等等


上一篇
[Day 04] Route-urls.py
下一篇
[Day 06] Database migrate
系列文
使用 Django 開發網頁系統30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言