FBV和CBV
简单说,fbv用函数写视图,cbv则是用类来写。一般的项目推荐用fbv,前后端分离的项目,微信小程序会用
HTML模版
# 1.寻找demo.html,去哪里找? 优先DIRS,再去已注册APP的templates
# 2.读取文件内容 + 参数 => 模板渲染(替换)【模板语法】
# 3.封装到HttpResponse的请求体中
# 4.后续给用户返回
demo.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{{ v1 }}
</body>
</html>
views.py
from django.shortcuts import render
# Create your views here.
def demo(request):
# 业务处理,获取到值
user_list = ["admin", "qwe123"]
# 1.寻找demo.html 优先DIRS,再去已注册APP的templates
# 2.读取文件内容 + 参数 => 模板渲染(替换)【模板语法】
# 3.封装到HttpResponse的请求体中
# 4.后续给用户返回
return render(request, "demo.html", {"v1": user_list})
也支持for循环:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{#{{ v1 }}#}
<h4>for循环</h4>
{% for item in v1 %}
<li>{{ item }}</li>
{% endfor %}
</body>
</html>
渲染的本质
namespace = {'name': 'admin', 'data': [18, 73, 84]}
code = '''def hellocute():return "name %s ,age %d" %(name,data[0],) '''
func = compile(code, '<string>', "exec")
exec(func, namespace)
result = namespace['hellocute']()
print(result)
info="""
def _execute():
_buffer = []
_buffer.append("<h1>")
_buffer.append(name)
_buffer.append("123")
_buffer.append("</h1>")
return "".join(_buffer)
"""
func = compile(info, '<string>', "exec")
exec(func, namespace)
result = namespace['_execute']()
print(result)
自定义模板函数
- app必须注册
- 创建templatetags的文件夹(名称千万不能改)
- 任意创建文件,内容
v1.py
from django.template.library import Library
register = Library()
@register.simple_tag()
def my_func(v1):
return "你好" + v1
{% load v1 %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{#{{ v1 }}#}
<h4>for循环</h4>
{% for item in v1 %}
<li>{{ item }}</li>
{% endfor %}
<div>{% my_func "张三" %}</div>
</body>
</html>
这里我遇到了报错:‘xxx‘ is not a registered tag library
这里解决https://blog.51cto.com/ruochen/5449546
返回html片段:
from django.template.library import Library
register = Library()
@register.simple_tag()
def my_func(v1):
return "你好" + v1
@register.inclusion_tag("inclu.html")
def my_inclu():
return {"x1": ["aa", "bb", "cc"]}
inclu.html:
<ul>
{% for item in x1 %}
<li>{{ item }}</li>
{% endfor %}
</ul>
{% load v1 %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{#{{ v1 }}#}
<h4>for循环</h4>
{% for item in v1 %}
<li>{{ item }}</li>
{% endfor %}
<div>{% my_func "张三" %}</div>
<div>{% my_inclu %}</div>
</body>
</html>
from django.template.library import Library
register = Library()
@register.simple_tag()
def my_func(v1):
return "你好" + v1
@register.inclusion_tag("inclu.html")
def my_inclu():
return {"x1": ["aa", "bb", "cc"]}
#一般用了做条件判断
@register.filter
def my_fil(v3):
return "hello!" + v3
{% load v1 %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{#{{ v1 }}#}
<h4>for循环</h4>
{% for item in v1 %}
<li>{{ item }}</li>
{% endfor %}
<div>{% my_func "张三" %}</div>
<div>{% my_inclu %}</div>
<div>{{ "Niko" | my_fil }}</div>
</body>
</html>