Django template

Tynam.Yang 2020-11-16 10:06:58
django template


Definition

DTL(django Tempalte language) yes Django The template language comes with . Django Support Jinja2 Wait for other template engines .DTL A template is a special syntax HTML file , Can be Django compile , Origin parameters , Dynamic data . After compiling , Generate an ordinary HTML file , Then send it to the client .

stay Django Provided in render , Directly render the template as a string and wrap it as HttpResponse object .views The following example is as follows :

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

Template search order

Newly added   app Need to be in settings To register :

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'book',
]

Template file search :

First of all, it will be on the project templates The lookup .
Second, in your own place app Under the templates Search for .
Finally, in other app Next lookup .
If... In the following code APP_DIRS The value of is False, Not in app Let's search , Only in the project templates The lookup .

TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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',
],
},
},
]

Parameter passing

stay render There is context Parameters are passed as parameters .
for example views by :

def index(request):
context = {
'username': 'ty'
}
return render(request,'index.html', context=context)

stay html Use two curly braces in {{ " Variable " }} reference :

<body>
{{ username }}
</body>

If it's hierarchical , For example, variables in a class , You can use point class.value To get .
For example, a dictionary , You can also use points to get dict.key . But if you use dict.keys What you get is all of the dictionary key. You can't go through brackets [] The form of acquisition .
For example, a list of , You can use subscripts to get list.index . Tuples are the same .

Commonly used labels

if label : It can also be combined with else Use it together , But there needs to be an end endif, You can use the basic operator == ,!=, >= etc. .

{% if number < 1 %}
<p> Less than 1</p>
{% if number == 1 %}
<p> be equal to 1</p>
{% else %}
<p> Greater than 1</p>
{% endif %}

for label : And Python Of for The sentence situation is similar to , Circular grammar is for X in Y ,Y It's a sequence to iterate, and X Is the name of the variable used in each particular loop . In every cycle , The template system will render in {% for %} and {% endfor %} Between all the content .

<ul>
{% for athlete in athlete_list %}
<li>{{ athlete.name }}</li>
{% endfor %}
</ul>

url label
url The back is path Medium name value .

<a href="{ % url 'urlname' % }"></a>

It can also be in url Add parameters in :

<a href="{ % url 'urlname' id='3' % }"></a>

filter

stay DTL Call form of function is not supported in , So you can't pass parameters to functions . And the filter is actually a function , The parameters to be processed can be processed , And you can receive an extra parameter .
add: Add the parameter passed in to the original value .

{{ value|add:'3' }}

cut: Remove string , Be similar to replace function .

{{ value|cut:" " }}

date: Date format , Put a date in a format , Format as a string .

# data 
context = {
”birthday“:datetiem.now()
}
# Templates 
{{ birthday|date:"Y/m/d" }}

Other ways to format time .

Format characters

describe

Example

Y

Four digit year

2018

m

Two digit months

01-12

n

month ,1-9 There is no 0 Prefix

1-12

d

Two digit days

01-31

j

God , however 1-9 There is no 0 Prefix

1-31

g

Hours ,12 Hour format ,1-9 There is no 0 Prefix

1-12

h

Hours ,12 Hour format ,1-9 There is 0 Prefix

01-12

G

Hours ,24 Hour format ,1-9 There is no 0 Prefix

1-23

H

Hours ,24 Hour format ,1-9 There is 0 Prefix

01-23

i

minute ,1-9 There is 0 Prefix

00-59

s

second ,1-9 There is 0 Prefix

00-59

Other filters

filter explain
addslashes Add slashes
capfirst title case
center Center text
default Set the default value
default_if_none by None Set the default value
dictsort Dictionary sort
dictsortreversed Dictionary reverse sort
divisibleby Divide judgment
escape escape
escapejs escape js Code
filesizeformat File size humanized display
first First element
floatformat Floating point format
force_escape Force immediate escape
get_digit Get numbers
iriencode transformation IRI
join Character list links
last the last one
length length
length_is The length is equal to
linebreaks Row conversion
linebreaksbr Row conversion
linenumbers Line number
ljust Align left
lower A lowercase letter
make_list Split into character list
phone2numeric Phone number
pluralize Plural form
pprint debugging
random Random access
rjust Right alignment
safe Safety confirmation
safeseq List security confirmation
slice section
slugify convert to ASCII
stringformat String formatting
striptags Remove HTML The label in
time Time format
timesince From when
timeuntil When and how long
title All words are capitalized
truncatechars Truncated characters
truncatechars_html Truncated characters
truncatewords Truncate words
truncatewords_html Truncate words
unordered_list Unordered list
upper Capitalization
urlencode escape url
urlize url Turn to a clickable link
urlizetrunc urlize How to truncate
wordcount Word count
wordwrap Word wrapping
yesno take True,False and None, Mapping to a string ‘yes’,‘no’,‘maybe’

Template inheritance

Write a public html file , Inheriting the common module in the sub template can achieve the purpose of reuse . Use... In submodules { % extends 'xxx.html' % }
In public html In file , have access to block As an interface , Fill in the contents of the common module area . The common module will be filled and covered block Chinese content .

# Common module ,block The back is block name 
{% block blockname %}
{% endblock %}
# Sub module 

{ % extends 'xxx.html' % }
{% block blockname %}
{% endblock %}

If the public module block There is no hope that it will be covered , You can add block.super Are identified .

# Common module ,block The back is block name 
{% block blockname %}
{{ block.super }}
This is code that won't be covered
{% endblock %}

Load static file

1、 Make sure django.contrib.staticfiles Has been added to settings Medium INSTALLED_APPS
2、 Make sure settings Set up in STATIC_URL = '/static/'
3、 On the installed app Next create a folder called static
4、 If some static files are not consistent with any app Hooked up , Can be in settings Add STATICFILES_DIRS

STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static")
]

5、 Used in templates load Label load static label .

 {% load static %}
<link rel="stylesheet" href="{ % static 'style.css' % }">

6、 If you don't want to load static files in the template each time, use load load static label , So it can be settings Medium TEMPLATES/OPTIONS Add built-in tags in the ,builtins

'builtins':['django.templatetags.static']

7、 If not in settings Under the INSTALLED_APPS Add django.contrib.staticfiles , Then you need to manually request the static file url Mapping to the path of a static file .

 

版权声明
本文为[Tynam.Yang]所创,转载请带上原文链接,感谢

  1. 小白量化投资交易入门课(python入门金融分析)
  2. Python:PyCharm选择性忽略PEP8警告
  3. Python: pychar selectively ignores pep8 warnings
  4. Django-模板
  5. Python正则表达式大全
  6. 最全Python正则表达式来袭
  7. A python knowledge for Xiaobai
  8. 2. Flexible pandas index
  9. 1. Get to know pandas
  10. See how I use Python to create a magic with baby (one play can play for a day)?
  11. Wow, python can do real-time translation
  12. Python经典编程习题100例
  13. 100 examples of Python classic programming exercises
  14. Invincible, with Python for English teachers to develop a magic tool for English composition correction (support primary school to IELTS)
  15. 抖音数据采集教程,最全python库selenium自动化使用
  16. Pandas 11-综合练习
  17. Pandas 11 - comprehensive exercises
  18. Pandas基础|用户游览日志时间合并排序
  19. python自学 第三章 python语言基础之保留字、标识符与内置函数
  20. python学习例程3-函数
  21. Python GUI 之Tkinter小结 - 知乎
  22. Pandas foundation | user travel log time merge sort
  23. Chapter 3 reserved words, identifiers and built-in functions of the foundation of Python
  24. Tkinter summary of Python GUI - Zhihu
  25. 【Python常用包】itertools
  26. Itertools
  27. [Python] Matplotlib 图表的绘制和美化技巧
  28. Drawing and beautifying skills of [Python] Matplotlib chart
  29. Drawing and beautifying skills of [Python] Matplotlib chart
  30. Python序列之列表(一)
  31. Python解析库lxml与xpath用法总结
  32. Python解析库lxml与xpath用法总结
  33. Usage Summary of Python parsing library lxml and XPath
  34. Usage Summary of Python parsing library lxml and XPath
  35. Python web/HTML GUI
  36. Why is sanic better than Django flame?
  37. Wechat applet Python sends subscription message
  38. Invincible, with Python for English teachers to develop an English composition correction artifact (support primary school to IELTS)
  39. How can I use Python to create a magic with children (one can play for one day)?
  40. Pandas module
  41. Machine learning in Python - Boston house price forecast
  42. 50 Great Python modules
  43. Share the survival status of Python practitioners and tell you the real salary of general programmers
  44. Pandas basic operation update
  45. Python Programming day02 Python operator
  46. Usage Summary of Python parsing library lxml and XPath
  47. 1. First meeting pandas
  48. Conversion between Python and base conversion between Python and base
  49. Basics of Python
  50. Fundamentals of python (XIV): errors and exceptions
  51. Fundamentals of python (8): time related modules
  52. Fundamentals of python (I): necessary knowledge for getting started
  53. Operators in Python 3
  54. The list of national computer non graduate schools (captured by Python), just look at this one!
  55. Python data visualization: Seaborn
  56. Quick start pandas (lower)
  57. Operators in Python 3
  58. Python tarfile module
  59. Python basic syntax