首页 > 其他 > 详细

django--模板继承、组件、自定义标签

时间:2019-09-27 18:50:06      阅读:66      评论:0      收藏:0      [点我收藏+]

模板继承

base.html--被继承的文件(模板)
~~~html
<!DOCTYPE html>



{% block title %}My amazing site{%/span> endblock %}

{% block content %}
  • test
  • test
{% endblock %}

~~~
home.html--继承模板代码(保证两个文件在同一目录)
~html
{% extends "base.html" %}
{% block content %}
{{ block.super }} # 继承
{% endblock %}
~
使用继承的一些提示:

  • 如果你在模版中使用 {% extends %} 标签,它必须是模版中的第一个标签。其他的任何情况下,模版继承都将无法工作,模板渲染的时候django都不知道你在干啥。
  • 在base模版中设置越多的 {% block %} 标签越好。请记住,子模版不必定义全部父模版中的blocks,所以,你可以在大多数blocks中填充合理的默认内容,然后,只定义你需要的那一个。多一点钩子总比少一点好。
  • 如果你发现你自己在大量的模版中复制内容,那可能意味着你应该把内容移动到父模版中的一个 {% block %} 中。
  • If you need to get the content of the block from the parent template, the {{ block.super }} variable will do the trick. This is useful if you want to add to the contents of a parent block instead of completely overriding it. Data inserted using {{ block.super }} will not be automatically escaped (see the next section), since it was already escaped, if necessary, in the parent template. 将子页面的内容和继承的母版中block里面的内容同时保留

组件

需要什么页面导入即可,导入语法:
{% include "navbar.html" %}

自定义标签和过滤器

1.在settings中的INSTALLED_APPS配置当前app,不然django无法找到自定义的simple_tag.
2.在app中创建templatetags模块(模块名只能是templatetags,一定要在app中创建)
3.创建任意.py文件,如:tags.py


tags.py
~~~python
from django import template

register = template.Library() # register的名字是固定的,不可改变

@register.filter
def addtest(n1): # {{ name|addtest }}
‘‘‘
无参数的过滤器
:param n1: 变量的值 管道前面的
:param n2: 传的参数 管道后面的,如果不需要传参,就不要添加这个参数
:return:
‘‘‘

return n1+'test'

@register.simple_tag
def huxtag(n1,n2): # {{ name|huxtag:‘admin‘ }}
‘‘‘
自定义标签没有参数个数限制
:param n1: 变量的值 管道前面的
:param n2: 传的参数 管道后面的,如果不需要传参,就不要添加这个参数
:return:
‘‘‘
return n1+n2

~~~
如果在html页面使用时,需要在页面顶部引用
{% load tags %}
~~~html
{% load tags %}
<!DOCTYPE html>



Title