Django03模板渲染方式

  1. 模板路径
  2. 渲染方式
  3. 使用render进行渲染

setting.py中模板路径配置:

 1 TEMPLATES = [
 2     {
 3         'BACKEND': 'django.template.backends.django.DjangoTemplates',
 4         'DIRS': [os.path.join(BASE_DIR, 'templates')],
 5         'APP_DIRS': True,
 6         'OPTIONS': {
 7             'context_processors': [
 8                 'django.template.context_processors.debug',
 9                 'django.template.context_processors.request',
10                 'django.contrib.auth.context_processors.auth',
11                 'django.contrib.messages.context_processors.messages',
12             ],
13         },
14     },
15 ]

1.直接将html字符串硬编码HttpResponse

def index_1(request):
    return HttpResponse('<h1>Hello Django World!</h1>')

2.django.template.loader 定义了函数以加载模板

get_template(template_name,using = None)

该函数使用给定的名称加载模板并返回一个Template 对象.get_template()尝试获取每个模板直到有一个成功满足。

注意获取模板的顺序:先主项目的templates里面-->app的templates里面

def template_render(request):
    """04加入模板html"""
    t = get_template("hello_django.html")
    html = t.render()  #render()括号里面可遗传字典参数context
    return HttpResponse(html)

3.使用render进行渲染

def simple_render(request):
    """05加入模板html"""

    return render(request,"hello_django.html")
#render(request, template_name, context=None, content_type=None, status=None, using=None)

拓展namespace,app_name

在django 1.* include(arg, namespace=None, app_name=None)
使用  url(r'^t6/', include('t6.urls', namespace='t6')

在django 2.0  include(arg,namespace=None)

使用  path('news/', include(('apps.news.urls','news'), namespace='news')),

  

posted @ 2019-03-13 19:36  mhh4399  阅读(117)  评论(0)    收藏  举报