Python之Django模板
Posted 栈了一堆
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python之Django模板相关的知识,希望对你有一定的参考价值。
<html lang="en">
<head>
<meta charset="UTF-8">
<title>wyn templates</title>
</head>
<body>
<h1>{{ wyn_arg }}</h1>
<h2>{{ wyn_arg }}</h2>
<h3>{{ wyn_arg }}</h3>
</body>
</html>
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [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',
],
},
},
]
from django.shortcuts import render
def v_1(request):
message = 'hello smart_wyn ! this is a templates !'
return render(request, "wyn.html",{'wyn_arg':message})
views.py:
from django.shortcuts import render
def v_1(request):
message = ['hello smart_wyn !', 'this is a templates !']
return render(request, "wyn.html",{'arg_list':message})
wyn.html:
<html lang="en">
<head>
<meta charset="UTF-8">
<title>wyn templates</title>
</head>
<body>
<h1>{{ arg_list }}</h1> {#取出整个列表 #}
<h2>{{ arg_list.0 }}</h2> {#取出列表第0个元素 #}<h3>{{ arg_list.1 }}</h3> {#取出列表第1个元素 #}
/body>
</html>
</html>
运行结果如下:
views.py
from django.shortcuts import render
def v_1(request):
message = {'name':'smart_wyn','age':18}
return render(request, "wyn.html",{'arg_dict':message})
wyn.html:
<html lang="en">
<head>
<meta charset="UTF-8">
<title>wyn templates</title>
</head>
<body>
<h1>{{ arg_dict }}</h1> {#取出整个字典 #}
<h2>{{ arg_dict.name }}</h2> {#取出字典name的值 #}<h3>{{ arg_dict.age }}</h3> {#取出字典age的值 #}
/body>
</html>
</html>
运行结果如下:
for 标签
基本语法格式如下:
{% for %}
... display
{% endfor %}
views.py:
from django.shortcuts import render
def v_1(request):
message = [{'name':'han mei mei','age':18},
{'name':'li lin','age':23},
{'name':'xiao hua','age':31}]
return render(request, "wyn.html",{'arg_dl':message})
wyn.html:
<html lang="en">
<head>
<meta charset="UTF-8">
<title>wyn templates</title>
</head>
<body>
% for i in arg_dl %}
{% if i.age <= 18%}
<h1>{{ i.name }} juvenile</h1>
{% elif i.age > 18 and i.age < 30%}
<h1>{{ i.name }} youth</h1>
{% else %}
<h1>{{ i.name }} middle aged</h1>
{% endif %}
{% endfor %}
{% for i,j in arg_dl.0.items %}
<h2>{{ i }} : {{ j }}</h2>
% endfor %}/body>
</html>
</html>
<---------------- END -------------->
以上是关于Python之Django模板的主要内容,如果未能解决你的问题,请参考以下文章