목차
用户信息:
{% block headTitle %}{% endblock %}
嘿,这是继承了模版
{% block headTitle %}用户信息:{% endblock %}
{% block headTitle %}产品信息:{% endblock %}
백엔드 개발 파이썬 튜토리얼 python Django模板的使用方法

python Django模板的使用方法

Jun 10, 2016 pm 03:06 PM
django python 주형

模板是一个文本,用于分离文档的表现形式和内容。 模板定义了占位符以及各种用于规范文档该如何显示的各部分基本逻辑(模板标签)。 模板通常用于产生HTML,但是Django的模板也能产生任何基于文本格式的文档。
来一个项目说明
1、建立MyDjangoSite项目具体不多说,参考前面。
2、在MyDjangoSite(包含四个文件的)文件夹目录下新建templates文件夹存放模版。
3、在刚建立的模版下建模版文件user_info.html

<html>
  <meta http-equiv="Content-type" content="text/html; charset=utf-8">
  <title>用户信息</title>
  <head></head>
  <body>
    <h3 id="用户信息">用户信息:</h3>
    <p>姓名:{{name}}</p>
    <p>年龄:{{age}}</p>
  </body>
</html>
로그인 후 복사

说明:{{ name }}叫做模版变量;{% if xx %} ,{% for x in list %}模版标签。

4、修改settings.py 中的TEMPLATE_DIRS
导入import os.path
添加 os.path.join(os.path.dirname(__file__), ‘templates').replace(‘\\','/'),

TEMPLATE_DIRS = (
  # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
  # Always use forward slashes, even on Windows.
  # Don't forget to use absolute paths, not relative paths.
  #"E:/workspace/pythonworkspace/MyDjangoSite/MyDjangoSite/templates",
  os.path.join(os.path.dirname(__file__), 'templates').replace('\\','/'),
)

로그인 후 복사

说明:指定模版加载路径。其中os.path.dirname(__file__)为当前settings.py的文件路径,再连接上templates路径。
5、新建视图文件view.py

#vim: set fileencoding=utf-8:
#from django.template.loader import get_template
#from django.template import Context
#from django.http import HttpResponse
from django.shortcuts import render_to_response
def user_info(request):
  name = 'zbw'
  age = 24
  #t = get_template('user_info.html')
  #html = t.render(Context(locals()))
  #return HttpResponse(html)
  return render_to_response('user_info.html',locals())
로그인 후 복사

说明:Django模板系统的基本规则: 写模板,创建 Template 对象,创建 Context , 调用 render() 方法。

可以看到上面代码中注释部分
#t = get_template(‘user_info.html') #html = t.render(Context(locals()))
#return HttpResponse(html)
get_template(‘user_info.html'),
使用了函数 django.template.loader.get_template() ,而不是手动从文件系统加载模板。 该 get_template() 函数以模板名称为参数,在文件系统中找出模块的位置,打开文件并返回一个编译好的 Template 对象。
render(Context(locals()))方法接收传入一套变量context。它将返回一个基于模板的展现字符串,模板中的变量和标签会被context值替换。其中Context(locals())等价于Context({‘name':'zbw','age':24}) ,locals()它返回的字典对所有局部变量的名称与值进行映射。
render_to_response Django为此提供了一个捷径,让你一次性地载入某个模板文件,渲染它,然后将此作为 HttpResponse返回。

6、修改urls.py

from django.conf.urls import patterns, include, url
from MyDjangoSite.views import user_info
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
  # Examples:
  # url(r'^$', 'MyDjangoSite.views.home', name='home'),
  # url(r'^MyDjangoSite/', include('MyDjangoSite.foo.urls')),
  # Uncomment the admin/doc line below to enable admin documentation:
  # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
  # Uncomment the next line to enable the admin:
  # url(r'^admin/', include(admin.site.urls)),
  url(r'^u/$',user_info),
 
)
로그인 후 복사

7、启动开发服务器

基本一个简单的模版应用就完成,启动服务看效果!
效果如图:

模版的继承
减少重复编写相同代码,以及降低维护成本。直接看应用。
1、新建/templates/base.html

<html>
  <meta http-equiv="Content-type" content="text/html; charset=utf-8">
  <title>{% block title %}{% endblock %}</title>
  <head></head>
  <body>
    <h3 id="block-headTitle-endblock">{% block headTitle %}{% endblock %}</h3>
    {% block content %} {% endblock %}
    {% block footer %}
      <h3 id="嘿-这是继承了模版">嘿,这是继承了模版</h3>
    {% endblock%}
  </body>
</html>
로그인 후 복사

2、修改/template/user_info.html,以及新建product_info.html
urser_info.html

{% extends "base.html" %}
{% block title %}用户信息{% endblock %}
 
<h3 id="block-headTitle-用户信息-endblock">{% block headTitle %}用户信息:{% endblock %}</h3>
{% block content %}
<p>姓名:{{name}}</p>
<p>年龄:{{age}}</p>
{% endblock %}
로그인 후 복사

product_info.html

{% extends "base.html" %}
{% block title %}产品信息{% endblock %}
<h3 id="block-headTitle-产品信息-endblock">{% block headTitle %}产品信息:{% endblock %}</h3>
{% block content %}
  {{productName}}
{% endblock %}
로그인 후 복사

3、编写视图逻辑,修改views.py

#vim: set fileencoding=utf-8:
#from django.template.loader import get_template
#from django.template import Context
#from django.http import HttpResponse
from django.shortcuts import render_to_response
def user_info(request):
  name = 'zbw'
  age = 24
  #t = get_template('user_info.html')
  #html = t.render(Context(locals()))
  #return HttpResponse(html)
  return render_to_response('user_info.html',locals())
def product_info(request):
  productName = '阿莫西林胶囊'
  return render_to_response('product_info.html',{'productName':productName})
 
로그인 후 복사

4、修改urls.py

from django.conf.urls import patterns, include, url
from MyDjangoSite.views import user_info,product_info
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
  # Examples:
  # url(r'^$', 'MyDjangoSite.views.home', name='home'),
  # url(r'^MyDjangoSite/', include('MyDjangoSite.foo.urls')),
  # Uncomment the admin/doc line below to enable admin documentation:
  # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
  # Uncomment the next line to enable the admin:
  # url(r'^admin/', include(admin.site.urls)),
  url(r'^u/$',user_info),
  url(r'^p/$',product_info),
)
 
로그인 후 복사

5、启动服务效果如下:

以上就是本文的全部内容,希望对大家的学习有所帮助。

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

뜨거운 기사 태그

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

DeepSeek Xiaomi를 다운로드하는 방법 DeepSeek Xiaomi를 다운로드하는 방법 Feb 19, 2025 pm 05:27 PM

DeepSeek Xiaomi를 다운로드하는 방법

Google AI, 개발자를 위한 Gemini 1.5 Pro 및 Gemma 2 발표 Google AI, 개발자를 위한 Gemini 1.5 Pro 및 Gemma 2 발표 Jul 01, 2024 am 07:22 AM

Google AI, 개발자를 위한 Gemini 1.5 Pro 및 Gemma 2 발표

당신은 그에게 Deepseek에게 어떻게 물어 봐요 당신은 그에게 Deepseek에게 어떻게 물어 봐요 Feb 19, 2025 pm 04:42 PM

당신은 그에게 Deepseek에게 어떻게 물어 봐요

NET40은 어떤 소프트웨어인가요? NET40은 어떤 소프트웨어인가요? May 10, 2024 am 01:12 AM

NET40은 어떤 소프트웨어인가요?

DeepSeek을 검색하는 방법 DeepSeek을 검색하는 방법 Feb 19, 2025 pm 05:18 PM

DeepSeek을 검색하는 방법

브라우저 플러그인은 어떤 언어로 작성되어 있나요? 브라우저 플러그인은 어떤 언어로 작성되어 있나요? May 08, 2024 pm 09:36 PM

브라우저 플러그인은 어떤 언어로 작성되어 있나요?

DeepSeek을 프로그래밍하는 방법 DeepSeek을 프로그래밍하는 방법 Feb 19, 2025 pm 05:36 PM

DeepSeek을 프로그래밍하는 방법

프로그램 성능 최적화를 위한 일반적인 방법은 무엇입니까? 프로그램 성능 최적화를 위한 일반적인 방법은 무엇입니까? May 09, 2024 am 09:57 AM

프로그램 성능 최적화를 위한 일반적인 방법은 무엇입니까?

See all articles