HTML模板
HTML模板
希望数据 + 嵌套 HTML标签,返回给用户浏览器。
1 基本使用
-
编写
def demo(request): # 业务处理,获取到值 user_list = ["武沛齐","张开"] # 1.寻找demo.html,去哪里找? 优先DIRS,再去已注册APP的templates # 2.读取文件内容 + 参数 => 模板渲染(替换)【模板语法】 # 3.封装到HttpResponse的请求体中 # 4.后续给用户返回 return render(request,"demo.html",{"v1":user_list})
-
寻找
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.staticfiles', "apps.app01.apps.App01Config", "apps.www.apps.WwwConfig", ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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', ], }, }, ]
2 底层处理方式
namespace = {'name': 'wupeiqi', '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)
3 其他
1.继承
2.导入
3.常见问题和应用
- 页面的title问题
- 关于模板渲染的时机
4 自定义模板函数
-
app必须注册
-
创建templatetags的文件夹
-
任意创建文件,内容:
from django.template.library import Library register = Library() @register.simple_tag() def my_func(v1, v2, v3): return "哈哈哈哈" + v1 + v2 + v3 @register.inclusion_tag("xo.html") def my_xo(num): return {"x1": [item for item in num if item > 22]} @register.filter def my_tt(a1, a2): return "哈哈哈" + a1 + a2
-
调用
{% load xxx %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div>{{ name }}</div> <div>{{ num }}</div> <div>{% my_func "武沛齐" "张开" name %}</div> <div>{% my_xo num %}</div> <div>{{ "alex"|my_tt:"xxxx" }}</div> {% if "alex"|my_tt:"xxxx" %} <h1>真</h1> {% else %} <h1>家</h1> {% endif %} </body> </html>
-
片段:xo.html
<ul> {% for item in x1 %} <li>{{ item }}</li> {% endfor %} </ul>
本文作者:Sherwin
本文链接:https://www.cnblogs.com/sherwin1995/p/18406209
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步