其他分享
首页 > 其他分享> > django入门到精通⑤mako模板的使用

django入门到精通⑤mako模板的使用

作者:互联网

1.搭建基础环境

(python37_django2) D:\python\django_imooc_xiaobai>django-admin startproject mako_project

(python37_django2) D:\python\django_imooc_xiaobai>cd mako_project

(python37_django2) D:\python\django_imooc_xiaobai\mako_project>python manage.py startapp app

(python37_django2) D:\python\django_imooc_xiaobai\mako_project>pip install mako

2.编写基础函数

app/base_render.py

# _*_ coding:utf-8 _*_
# __author__ == 'jack'
# __date__ == '2020-12-31 11:56 AM'


from mako.lookup import TemplateLookup
from django.template import RequestContext
from django.conf import settings
from django.template.context import Context
from django.http import HttpResponse


def render_to_response(request, template, data=None):
    context_instance = RequestContext(request)
    path = settings.TEMPLATES[0]['DIRS'][0]
    lookup = TemplateLookup(
        directories = [path],
        output_encoding='utf-8',
        input_encoding='utf-8'
    )
    mako_template = lookup.get_template(template)

    if not data:
        data = {}

    if context_instance:
        context_instance.update(data)
    else:
        context_instance = Context(data)

    result = {}
    for d in context_instance:
        result.update(d)

    # data['csrf_token'] = '<input type="hidden" name="csrfmiddlewaretoken" value="{0}" />'\
    #      .format(request.META['CSRF_COOKIE'])
    return HttpResponse(mako_template.render(**result))

引入根路由

urls.py

from django.contrib import admin
from django.urls import path
from app.views import Test

urlpatterns = [
    path('admin/', admin.site.urls),
    path('test/', Test.as_view())
]

视图 app/views.py

# encoding:utf-8

from django.views.generic import View
from .base_render import render_to_response


class Test(View):
    TEMPLATE = 'test.html'

    def get(self, request):
        data = {'name': 'jack', 'age': 18}
        return render_to_response(request, self.TEMPLATE, data = data)

3.配置settings.py

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    # 关闭csrf
    # 'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]


TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
    # 引入模板
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        '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',
            ],
        },
    },
]

# 引入static目录

STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'), )

4.基础模板配置

基础模板
templates/base.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>${self.title()}</title>
    <link rel="stylesheet" href="">
    ${self.css()}
</head>
<body>
    ${self.content()}
</body>
</html>
<%def name="content()">
    ${self.main()}
    ${self.js()}

</%def>
<%def name="main()"></%def>

<%def name="title()"></%def>
<%def name="js()"></%def>
<%def name="css()"></%def>

继承页面
templates/extend.html

<%page args="local_content" />
<textarea>
    ${local_content}
</textarea>

测试页面
templates/test01.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
${name}
${age}

<%!
    from django.conf import settings
%>

${settings.TEMPLATES[0]['DIRS'][0]}
<br/>

%for i in range(20):
    <input type="text" value="${i}" />
%endfor

<br/>
<%!
    def name():
        return "my name is jack"
%>

<input style="display:block" type="text" name="username" value="${name()}" />

</body>
</html>

测试模板页面

templates/test.html

<%inherit file="base.html" />

<%def name="main()">
<%include file="extend.html" args="local_content='你好 mako'" />
<h1>hello mako</h1>
</%def>

<%def name="js()">
<script src="https://cdn.bootcss.com/jquery/2.2.0/jquery.js"></script>
</%def>

<%def name="title()">test</%def>
<%def name="css()">
<link rel="stylesheet" href="/static/test.css" />
</%def>

标签:mako,context,django,template,import,data,模板
来源: https://www.cnblogs.com/reblue520/p/14218552.html