1. render函数的参数
HelloWorld/templates/hello.html 文件代码:
<h1>{{ hello }}</h1>
HelloWorld/HelloWorld/view.py 文件代码:
from django.shortcuts import render
def hello(request):
context = {'hello': 'Hello World!'}
return render(request, 'hello.html', context)
context 字典中元素的键值 "hello" 对应了模板中的变量 "{{ hello }}"。
view.py下导入库:
from django.shortcuts import render
render(request, template_name, context=None, content_type=None, status=None, using=None)
Returns a HttpResponse whose content is filled with the result of calling django.template.loader.render_to_string() with the passed arguments.
此方法的作用---结合一个给定的模板和一个给定的上下文字典,并返回一个渲染后的 HttpResponse 对象。
通俗的讲就是把context的内容, 加载进templates中定义的文件, 并通过浏览器渲染呈现。
参数讲解:
request: 是一个固定参数。
template_name: templates 中定义的文件, 要注意路径名. 比如'templates\polls\index.html', 参数就要写‘polls\index.html’。
settings.py下要配置:
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',
],
},
},
]
context: 要传入文件中用于渲染呈现的数据, 默认是字典格式
content_type: 生成的文档要使用的MIME 类型。默认为DEFAULT_CONTENT_TYPE 设置的值。
status: http的响应代码,默认是200.
using: 用于加载模板使用的模板引擎的名称。
2. Django模板语言转义处理
如果hello.html模板中的"{{ hello }}"内容含html的话,django的模板系统默认会对输出进行转义(把内容转义成字符串),比如把<p>转义成了<p> ,然后再显示出来的时候就如实地显示为<p>。如下所示:
要解决这个问题只要把默认的自动转义关闭就好了。比如原本我们的模板代码是这样的:{{post.content}}
有两种方式可以解决:
方法一,关闭autoescape:
{% autoescape off %}
{{post.content}}
{% endautoescape %}
方法二,使用| safe过滤器:
{{post.content | safe}}