其他分享
首页 > 其他分享> > Django2.x - 模板过滤器

Django2.x - 模板过滤器

作者:互联网

Django 模板过滤器

# app 中的 urls.py
from django.urls import path, re_path
from . import views

urlpatterns = [
	path('test_filter', views.test_filter),
]


# app 中的 views.py
from django.template import loader
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render

def test_filter(request):
    name1 = 'admin'
    name2 = 'ROOT'
    num1 = 10
    str_script = "<script>alert('hello world')</script>"

    return render(request, 'test_filter.html', locals())


# app 中的 templates/test_filter.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>测试过滤器</title>
</head>
<body>
<h3>原变量: {{ name1 }}, upper后的变量值: {{ name1 | upper }}</h3>
<h3>原变量: {{ name2 }}, lower后的变量值: {{ name2 | lower }}</h3>
<h3>原变量: {{ num1 }}, add:'10'后的变量值: {{ num1 | add:'10' }}</h3>
<!--<h3>原变量: {{ str_script }}, safe后的变量值: {{ str_script | safe }}</h3>-->
<h3>原变量: {{ str_script }}</h3>
<h3>str_script safe后的变量值: {{ str_script | safe }}</h3>

</body>
</html>

模板的继承

# app 中的 urls.py
from django.urls import path, re_path
from . import views

urlpatterns = [
    path('base_index', views.base_view),
    path('music_index', views.music_view),
    path('sport_index', views.sport_view),
]


# app 中的 views.py
from django.template import loader
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render

def base_view(request):
    return render(request, 'base.html')

def music_view(request):
    return render(request, 'music.html')

def sport_view(request):
    return render(request, 'sport.html')


# app中的 templates/base.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    {% block mytitle %}
    <title>首页</title>
    {% endblock mytitle %}
</head>
<body>

{% block info %}
<h3>这是首页中的内容</h3>
{% endblock %}

<a href="/base_index">首页</a>
<a href="/music_index">音乐频道</a>
<a href="/sport_index">体育频道</a>
<br>
<h4>有问题请联系: xxxxxxxxxx</h4>
</body>
</html>


# app中的 templates/music.html
{% extends 'base.html' %}

{% block mytitle %}
<title>音乐频道</title>
{% endblock %}

{% block info %}
<h3>这是音乐频道的内容</h3>
{% endblock %}


# app中的 templates/sport.html
{% extends 'base.html' %}

{% block mytitle %}
<title>体育频道</title>
{% endblock %}

{% block info %}
<h3>这是体育频道的内容</h3>
{% endblock %}

标签:views,Django2,html,模板,base,过滤器,import,block
来源: https://www.cnblogs.com/gxfaxe/p/15017465.html