Django模板及其过滤器

  • 模板渲染
    注意模板文件需要在setting文件中配置路径
# 将HTML文件直接写入HttpRespones中
def index_1(request):
	return HttpResponse('<h1>这是django项目</h1>')

# django.template.loader定义了函数以加载模板
from django.template.loader import get_template
def index_2(request):
	tem = get_template('book/index.html')
	html = te.render()
	return HttpResponse(html)
	
# 使用render渲染
def index_3(request):
	return render(request, 'book/index.html')
  • 模板变量的引用
# views.py文件
li = [1,2,3,4,5]
dic = {
    
    'a':111,'b':222,'c':333}

def hello():
	return 'hello django!'

class Person:
	def __init__(self, name, age):
		self.name = name
		self.age = age

	def say(self):
		return 'this is python'

hua = Person('花花'18)


def tmp(request):
	return render(request, 'book/index.html', context={
    
    
						'book_name' : 'python'  # 字符串
						'hello' : hello      #函数
						'hua': hua # 类对象
						'say':hua.say  #类方法
						'li': li       # 列表
						'dic': dic      # 字典
					})
 # urls.py文件配置对应路由添加此路由
 path('tmp/',views.tmp, name = 'tmp') 

模板文件index.html
使用形式{ { book_name }}调用变量

  • 过滤器及其模板标签
# {
    
    {变量| 过滤器:参数}}

# views.py文件
from django.shortcuts import render

li = [2,4,6,8]
def test_1(request):
    return render(request, 'teacher/test_1.html', context={
    
    'li':li})


# urls.py文件
from django.urls import path
from . import views
urlpatterns =[
    path('test_1/', views.test_1)
]


# test_1.html文件
{
    
    #一定要先载入静态文件再使用#}

{
    
    % load static %}
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="{% static "teacher/index.css" %}">
</head>
<body>
<h1>this is bookstore</h1>
<h1>列表为{
    
    {
    
     li}}</h1>
<h1>列表为{
    
    {
    
     li | first}}</h1>
<p>django</p>
</body>
</html>


# index.css文件
p{
    
    
    color:red;
}
  • 效果图
    运行效果

猜你喜欢

转载自blog.csdn.net/qq_53075298/article/details/120088039