美文网首页python之路
django笔记(二)使用模板

django笔记(二)使用模板

作者: 非鱼2018 | 来源:发表于2021-01-23 14:44 被阅读0次

一,模板的使用

1.首先要建立templates文件夹,在app的目录,就是manage.py startapp **生成的目录下

image.png

如图,可以在下面再创建文件夹,引用模板时,路径为sample/hello.html

如果tenplates建立地方不对,在setting文件里,修改下templates的DIRS值

'DIRS': [os.path.join(BASE_DIR, 'templates')],

可以自己把basedie打印出来看看,然后拼装成真正的template路径

TEMPLATES = [

{

'BACKEND': 'django.template.backends.django.DjangoTemplates',

'DIRS': [],

2.建立模板文件

templates/sample下创建hello.html

<body>

<h1>{{ hello }}</h1>

<h1>{{ world}}</h1>

我们写两个变量,两个大括号

3.编写视图函数,views.py增加hello方法


from django.shortcuts import render,redirect,reverse

def hello(request):

  context = {}

  context['hello'] = 'nihao'

  context['name'] = 'feiyu1009'

return render(request, 'sample/hello.html', context)

使用render解析并返回模板,数据用字典格式传递,几个变量写几项,基本和jinja模板类似

但是jinjia在参数写法上还是比较方便的,可以直接用关键字参数

比如这里,在jijina可以这样写

template.render(hello=‘nihao’,name=‘feiyu1009’)

4.编写路由测试,可以看到变量已经全部替换了

re_path(r'^hello/$', views.hello),

http://127.0.0.1:8000/hello/

image.png

字典类型参数
hello2.html

<body>

<h1>hello {{ user.name }}</h1>

<h2>your age is {{ user.age }}</h2>

</body>

views.py

def hello2(request):

  users = {"name":'feiyu1009',"age":28}

  return render(request, 'sample/hello2.html', {"user":users})

re_path(r'^hello2/$', views.hello2),

image.png

二.过滤器

在标签中可以使用过滤器来修改变量,使用|

如{{ 变量名 | 过滤器:可选参数 }}

比如{{value|lower}}:变量小写

{{ value|add:"2" }}:变量加2

{{ value|cut:" " }}:移除空白字符

{{ value|cut:"abc" }}:移除所有abc字符

{{ birthday|date:"Y/m/d" }}

{{ value|default:"nothing" }}

{{ value|first }}

{{ value|last }}

{{ value|join:"/" }

{{value|safe}}

{{ some_list|slice:"2:" }}

{{ value|striptags }}

{{ value|truncatechars:5 }}

{{ value|truncatechars_html:5 }} 保留html标签

{{ value|linenumber}}

{{ value|linebreaks}} 行用
包裹

这里介绍的挺全的

https://www.cnblogs.com/TF511/p/10253997.html

*自定义过滤器:

比如变量中包含多行,我想显示变量的第一行,貌似过滤器没有类似splitesline()这种,自己定义个

1.创建templatetags,创建py文件

使用register.filter装饰器定义自定义标签

  1. image.png

2.模板中load下,如果有继承模板,则写daoextends语句下面

{% extends 'myapp/base.html' %}

{% load user_define %}

使用

{{ entry.text|splitlines|}}

参考菜鸟教程

https://www.runoob.com/django/django-template.html

三.标签的使用

for标签

{% for entry in content %}

{{ entry.text|linebreaks }}

{{entry.create_date}}

{% empty %}

<p>There are no entries for this topic yet.</p>

{% endfor %}

给标签增加一个 reversed 使得该列表被反向迭代:

{% for athlete in athlete_list reversed %}...{% endfor %}

if else标签

{% if condition1 %}

... display 1{% elif condition2 %}

... display 2{% else %}

... display 3{% endif %}

ifequal标签

{% ifequal section 'sitenews' %}

<h1>Site News</h1>{% else %}

<h1>No News Here</h1>{% endifequal %}

注释标签

{# 这是一个注释 #}

include标签

{% include "nav.html" %}

模板继承

{% extends "父模板路径"%}

{ % block 名称 % }内容

{% endblock 名称 %}

相关文章

网友评论

    本文标题:django笔记(二)使用模板

    本文链接:https://www.haomeiwen.com/subject/cyrnaktx.html