django框架-6模板

模板

将应用learn加入到setting.py中的INSTALLED_APPS中
INSTALLED_APPS = [
    # 'polls.apps.PollsConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'polls',
    'learn',
]
打开learn/views.py写一个首页的视图
# coding:utf-8
from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
def index(request):
    return render(request,'index.html')
learn下新建模板目录templates,在templates下创建index.html文件



    欢迎学习django


        aaaaaaaaaaaaaaaa


页面展示
django框架-6模板_第1张图片
Paste_Image.png
传递参数,修改views.py,修改部分如下:
def index(request):
    content = '欢迎欢迎,热烈欢迎'
    return render(request,'index.html',{'content':content})
修改模板index.html ,修改部分如下:

{{ content }}

页面展示
django框架-6模板_第2张图片
Paste_Image.png

模板中的循环、条件判断、过滤器等请参考下一节

补充

⽹站模板的设计,⼀般的,我们做⽹站有⼀些通⽤的部分,⽐如 导航,底部,访问统计代码等等 nav.html, bottom.html, tongji.html

可以写一个base.html来包含这些通用文件(include)
代码如下:

###view.py文件

# coding:utf-8
from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
def index(request):
    title = '欢迎登陆'
    content = '欢迎欢迎,热烈欢迎'
    return render(request,'learn/index.html',{'title':title,'content':content})

模板目录结构

django框架-6模板_第3张图片
Paste_Image.png

模板html代码





    {% block title %}{{ title }}{% endblock %}


{% include 'public/nav.html' %}
{% block content%}
这是默认内容
{% endblock %} {% include 'public/button.html' %} {% include 'public/tongji.html' %} {% extends 'public/base.html' %} {% block title %}{{ title }}{% endblock %} {% block content %} {% include 'public/ads.html' %}
{{ content }}
{% endblock %}

页面展示

django框架-6模板_第4张图片
Paste_Image.png

你可能感兴趣的:(django框架-6模板)