Django - 模板标签详解

2018-12-09  本文已影响0人  前端程序猿

接着上一篇 urls与视图详解 继续往下讲

一、模板查找路径

mysite/setting.py: 模板查找的优先级最高为如下配置

TEMPLATES = [
    {
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
    },
]

其次是,在各自的 app 中, 注意, 需要在 INSTALLED_APPS 中注册后才能起作用:

INSTALLED_APPS = [
    'front',
]

TEMPLATES = [
    {
        'APP_DIRS': True,
    },
]

最后如果在当前 app 中还找不到模板,会到其它已安装的 app 中查找, 如果还找不到就会报错了!

二、render_to_string

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        body {
            color: #f00;
        }
    </style>
</head>
<body>
佛曰: 我执, 是痛苦的根源!
</body>
</html>
 path('', views.index, name='index'),
from django.template.loader import render_to_string
from django.http import HttpResponse


def index(request):
    # 在 mysite/settings.py 配置了项目模板路径
    html = render_to_string("index.html")
    return HttpResponse(html)

三、render

render_to_stringHttpResponse 组合的快捷方式, 可 pycharm 查看 render 的实现如下:

def render(request, template_name, context=None, content_type=None, status=None, using=None):
    content = loader.render_to_string(template_name, context, request, using=using)
    return HttpResponse(content, content_type, status)

修改 front/views.py

from django.shortcuts import render


def index(request):
    return render(request, 'index.html')

四、模板变量

可以通过render 函数的 context 参数,给模板传递数据

模板中,不支持中括号语法,只能通过 . 语法获取

五 常用的模板标签

所有标签都需要用 {%%} 进行包裹

* 循环列表

    修改 `front/views.py` 
    ```py
    context = {
            'books': ['深入理解ES6', 'JavaScript权威指南', 'JavaScript语言精粹']
        }
    ```

    修改 `templates/index.html`  

    ```html
    <ul>
        {% for book in books %}
            <li>{{ book }}</li>
        {% endfor %}
    </ul>
    ```  

* 反向循环列表  `reversed`

    修改 `templates/index.html`  

    ```html
    {% for book in books reversed %}
        <li>{{ book }}</li>
    {% endfor %}
    ```  
上一篇 下一篇

猜你喜欢

热点阅读