温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Django基础知识之 模板配置和输出

发布时间:2020-07-21 11:19:00 来源:网络 阅读:192 作者:ckllf 栏目:编程语言

  一,get_template 函数

  from django.template.loader import get_template

  from django.http import HttpResponse

  import datetime

  def temp_test(request):

  now = datetime.datetime.now()

  t = get_template('temp_test.html')

  html = t.render({'current_date': now})

  return HttpResponse(html)

  模板输出:

  It is now {{ current_date }}

  get_template() 函数以模板名称为参数,在文件系统中找出模块的位置,打开文件并返回一个编译好的Template 对象

  二,render_to_response() 渲染模板

  from django.shortcuts import render_to_response

  import datetime

  def current_datetime(request):

  now = datetime.datetime.now()

  return render_to_response('current_datetime.html', {'current_date': now})

  render_to_response() 的第一个参数必须是要使用的模板名称。 如果要给定第二个参数,那么该参数必须是为该模板创建 Context 时所使用的字典。 如果不提供第二个参数, render_to_response() 使用一个空字典。

  三,locals() 技巧

  from django.shortcuts import render_to_response

  import datetime

  def temp_test(request):

  now = datetime.datetime.now()

  return render_to_response('temp_test.html', locals())

  locals() 的值,它囊括了函数执行到该时间点时所定义的一切变量

  此时对应html输出的格式应该为:

  It is now {{ now }}

  四,get_template()中使用子目录

  from django.shortcuts import render_to_response

  import datetime郑州妇科医院 http://www.sptdfk.com/

  def temp_test(request):

  now = datetime.datetime.now()

  return render_to_response('member/temp_test.html', locals())

  只需在调用 get_template() 时,把子目录名和一条斜杠添加到模板名称之前

  由于 render_to_response() 只是对 get_template() 的简单封装, 你可以对 render_to_response() 的第一个参数做相同处理

  五,模板包含和模板继承

  1,模板包含:include(); 公共头部,公共尾部,以当前模板目录路径为准

  {% include 'common/nav.html' %}

  It is now {{ now }}

  2,模板继承:block 用法

  概念:模板继承就是先构造一个基础框架模板,而后在其子模板中对它所包含站点公用部分和定义块进行重载

  My helpful timestamp site

  {% block content %}{% endblock %}

  {% block footer %}

  Thanks for visiting my site.

  {% endblock %}

  所有的 {% block %} 标签告诉模板引擎,子模板可以重载这些部分。 每个 {% block %} 标签所要做的是告诉模板引擎,该模板下的这一块内容将有可能被子模板覆盖。

  则子模板就可以更改为:

  {% extends "base.html" %}

  {% block title %}The current time{% endblock %}

  {% block content %}

  It is now {{ current_date }}.

  {% endblock %}

  功能核心点:

  1,如果在模板中使用 {% extends %} ,必须保证其为模板中的第一个模板标记。 否则,模板继承将不起作用。

  2,一般来说,基础模板中的 {% block %} 标签越多越好。 记住,子模板不必定义父模板中所有的代码块,因此可以用合理的缺省值对一些代码块进行填充,然后只对子模板所需的代码块进行(重)定义

  3,如果需要访问父模板中的块的内容,使用 {{ block.super }} 这个标签,这一个魔法变量将会表现出父模板中的内容。 如果只想在上级代码块基础上添加内容,而不是全部重载,该变量就显得非常有用。

  4,不允许在同一个模板中定义多个同名的 {% block %} 。

  5,{% extends %} 对所传入模板名称使用的加载方法和 get_template() 相同。 也就是说,会将模板名称被添加到 TEMPLATE_DIRS 设置之后。

  6,多数情况下, {% extends %} 的参数应该是字符串,但是如果直到运行时方能确定父模板名,这个参数也可以是个变量


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI