在使用模版之前,我们要先在 settings.py 搜寻 TEMPLATES ,我们会看到以下设定:
请在 DIRS 中加入os.path.join(BASE_DIR, 'templates')
,如下所示:
'DIRS': [os.path.join(BASE_DIR, 'templates')]
是指到 BASE_DIR/templates 文件夹中去取模板,指定公用的 templates 路径让所有 apps 都可以调用,非常方便。
接着,建立一个 templates 的资料夹,并在里面建立一个 hello_world.html
现在,我们的档案结构如下:
hello_world.html :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>hello_world</title>
</head>
<body>
<h1>hello_world!</h1>
</body>
</html>
然後进入 myapp/views.py 中,修改 hello_world:
from django.shortcuts import render
from django.http import HttpResponse
def hello_world(request):
return render(request, 'hello_world.html') #修改
def add(request, a, b):
s = int(a) + int(b)
return HttpResponse(s)
之後我们前往 http://127.0.0.1:8000/hello/ ,就能看见 template 回传的 hello_world 页面喔!
接下来,让我们来玩一点变化。
修改 myapp/views.py 中的 hello_world:
def hello_world(request): #修改
a = 10
b = 5
s = a + b
d = a - b
p = a * b
q = a / b
return render(request, 'hello_world.html',locals())
locals()函数会以字典类型返回当前位置的全部局部变量。
因此使用locals()就不用一个一个手动输入欲回传的变量罗~
修改 hello_world.html :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>hello_world</title>
</head>
<body>
<h1>hello_world!</h1>
<p>a = {{a}}</p>
<p>b = {{b}}</p>
<p>a + b = {{s}}</p>
<p>a - b = {{d}}</p>
<p>a * b = {{p}}</p>
<p>a / d = {{q}}</p>
</body>
</html>
{{<variable_name>}} 是在 Django Template 中显示变数的语法。
接着,当我们再次前往 http://127.0.0.1:8000/hello/ :
我们可以发现,我们在 views.py 中修改的 hello_world 里面的参数成功传到页面上了!
今天的介绍就到这里,明天就来建立 Django 模型(Model) 吧!
前言 今日的程序码 => GITHUB 这次要来介绍 Flutter 的 Cloud Mess...
动机 大家好,这是我第一次参加铁人赛! 在过去八年多的工作中,我主要工作内容为资料工程与数据分析产出...
如果你问上班族,公司的网路稳不稳?喜不喜欢视讯开会?大概八成以上持否定的态度。另外,在号称大云端、大...
原始题目 Evaluate the value of an arithmetic expressio...
引言 不好意思,作者总是有说不完的序言! 「机派X」的由来源自於无人机的机、树莓派的派还有 Linu...