python + django 搭建网页(尝试3):模板


参考:
[1] https://www.runoob.com/django/django-template.html

1. 视图模板

设置视图模板是为了使“数据与视图分离”。

1.1 设置路径,包括 templates 文件夹

settings.py 中
'DIRS': [os.path.join(BASE_DIR, 'templates')], # 修改位置

1.2 编辑模板

templates/runoob.html 中:

{{ hello }}

1.3 设置动作函数

views.py 中:

def runoob(request):
    context          = {}
    context['hello'] = 'Hello World!'
    return render(request, 'runoob.html', context)

1.4 关联 url

urls.py 中:

urlpatterns = [
    path('runoob/', views.runoob),
]

2. Ref. [1] 剩余内容中有意思的点

Ref. [1] 中还有很多关于模板的内容,但大多数我估计用不着,所以只摘录一点点似乎用得着的:

2.1 date

动作函数:

def runoob(request):
    import datetime
    now  =datetime.datetime.now()
    return render(request, "runoob.html", {"time": now})

runoob.html:

{{ time|date:"Y-m-d" }}

效果:

2020-05-16

2.2 safe

Django 会自动对 views.py 传到 HTML 文件中的标签语法进行转义,令超链接语义失效。加 safe 过滤器是告诉 Django 该数据是安全的,不必对其进行转义,可以让该数据语义生效。
例如,views.py 中:

def runoob(request):
    views_str = "点击跳转"
    return render(request, "runoob.html", {"views_str": views_str})

runoob.html中:

{{ views_str|safe }} # 加这个 safe 才会有超链接

2.3 条件判断

{% if condition1 %}
   ... display 1
{% elif condition2 %}
   ... display 2
{% else %}
   ... display 3
{% endif %}

可以嵌套使用。例如 views.py 中:

def runoob(request):
    views_num = 88
    return render(request, "runoob.html", {"num": views_num})

runoob.html 中:

{%if num > 90 and num <= 100 %}
优秀
{% elif num > 60 and num <= 90 %}
合格
{% else %}
一边玩去~
{% endif %}

2.4 循环语句

{% for athlete in athlete_list %}
    
  • {{ athlete.name }}
  • {% endfor %}

    例如:views.py 中:

    def runoob(request):
        views_list = ["菜鸟教程","菜鸟教程1","菜鸟教程2","菜鸟教程3",]
        return render(request, "runoob.html", {"views_list": views_list})
    

    runoob.html 中:

    {% for i in views_list %}
    {{ i }}
    {% endfor %}
    

    感觉如果能学一下 html 语言,会比较有帮助。

    2.5 {% empty %}:循环为空时执行

    例如:

    {% for i in listvar %}
        {{ forloop.counter0 }}
    {% empty %}
        空空如也~
    {% endfor %}
    

    2.6 配置静态文件(css, js, 图片, 插件)

    • 根目录下创建目录 statics
    • settings 最下方添加
    STATIC_URL = '/static/' # 别名 
    STATICFILES_DIRS = [ 
        os.path.join(BASE_DIR, "statics"), 
    ]
    
    • statics 下创建目录:css, js, images, plugins
    • bootstrap 框架放入 plugins (??不懂bootstrap是啥)
    • 在 html 的 head 标签中引入 bootstrap (?这个也没懂)

      例子:runoob.html 中加入
    {% load static %}
    {{name}}runoob-logo
    

    就可以在网页上显示 images/runoob-logo.png。
    另外,可以控制图片的高度和宽度,用百分比也可以:

    QFNUPHYS-logo
    

    使用了 width = "100%",所以图片会自动填充。

    相关