Django temple渲染

简介: from django.template import Context, Templatet = Template('My name is {{ name }}.

from django.template import Context, Template
t = Template('My name is {{ name }}.')
c = Context({'name': 'Stephane'})
t.render(c)

from django.template import Template, Context
raw_template = """<p>Dear {{ person_name }},</p>
...
... <p>Thanks for placing an order from {{ company }}. It's scheduled to
... ship on {{ ship_date|date:"F j, Y" }}.</p>
...
... {% if ordered_warranty %}
... <p>Your warranty information will be included in the packaging.</p>
... {% else %}
... <p>You didn't order a warranty, so you're on your own when
... the products inevitably stop working.</p>
... {% endif %}
...
... <p>Sincerely,<br />{{ company }}</p>"""
t = Template(raw_template)
import datetime
c = Context({'person_name': 'John Smith',
... 'company': 'Outdoor Equipment',
... 'ship_date': datetime.date(2009, 4, 2),
... 'ordered_warranty': False})
t.render(c)
u"<p>Dear John Smith,</p>\n\n<p>Thanks for placing an order from Outdoor
Equipment. It's scheduled to\nship on April 2, 2009.</p>\n\n\n<p>You
didn't order a warranty, so you're on your own when\nthe products
inevitably stop working.</p>\n\n\n<p>Sincerely,<br />Outdoor Equipment
</p>"

字典渲染

from django.template import Template, Context
person = {'name': 'Sally', 'age': '43'}
t = Template('{{ person.name }} is {{ person.age }} years old.')
c = Context({'person': person})
t.render(c)
u'Sally is 43 years old.'

日期渲染

from django.template import Template, Context
import datetime
d = datetime.date(1993, 5, 2)
d.year
Dear {{ person_name }},</p>
...
... <p>Thanks for placing an order from {{ company }}. It's scheduled to
... ship on {{ ship_date|date:"F j, Y" }}.</p>
...
... {% if ordered_warranty %}
... <p>Your warranty information will be included in the packaging.</p>
... {% else %}
... <p>You didn't order a warranty, so you're on your own when
... the products inevitably stop working.</p>
... {% endif %}
...
... <p>Sincerely,<br />{{ company }}</p>"""
>>> t = Template(raw_template)
>>> import datetime
>>> c = Context({'person_name': 'John Smith',
... 'company': 'Outdoor Equipment',
... 'ship_date': datetime.date(2009, 4, 2),
... 'ordered_warranty': False})
>>> t.render(c)
u"<p>Dear John Smith,</p>\n\n<p>Thanks for placing an order from Outdoor
Equipment. It's scheduled to\nship on April 2, 2009.</p>\n\n\n<p>You
didn't order a warranty, so you're on your own when\nthe products
inevitably stop working.</p>\n\n\n<p>Sincerely,<br />Outdoor Equipment
</p>"

字典渲染
>>> from django.template import Template, Context
>>> person = {'name': 'Sally', 'age': '43'}
>>> t = Template('{{ person.name }} is {{ person.age }} years old.')
>>> c = Context({'person': person})
>>> t.render(c)
u'Sally is 43 years old.'

日期渲染
>>> from django.template import Template, Context
>>> import datetime
>>> d = datetime.date(1993, 5, 2)
>>> d.year
1993
d.month
5
d.day
2
t = Template('The month is {{ date.month }} and the year is {{ date.year }}.')
c = Context({'date': d})
t.render(c)
u'The month is 5 and the year is 1993.'

类属性渲染

from django.template import Template, Context
class Person(object):
... def init(self, first_name, last_name):
... self.first_name, self.last_name = first_name, last_name
t = Template('Hello, {{ person.first_name }} {{ person.last_name }}.')
c = Context({'person': Person('John', 'Smith')})
t.render(c)
u'Hello, John Smith.'

数组、列表渲染

from django.template import Template, Context
t = Template('Item 2 is {{ items.2 }}.')
c = Context({'items': ['apples', 'bananas', 'carrots']})
t.render(c)
u'Item 2 is carrots.'

方法调用,不加括号

from django.template import Template, Context
person = {'name': 'Sally', 'age': '43'}
t = Template('{{ person.name.upper }} is {{ person.age }} years old.')
c = Context({'person': person})
t.render(c)
u'SALLY is 43 years old.'

属性

from django.template import Context
c = Context({"foo": "bar"})
c['foo']
'bar'
del c['foo']
c['foo']
Traceback (most recent call last):
...
KeyError: 'foo'
c['newvariable'] = 'hello'
c['newvariable']
'hello'

判断语句
{% if today_is_weekend %}
<p>Welcome to the weekend!</p>
{% endif %}

{% if today_is_weekend %}
<p>Welcome to the weekend!</p>
{% else %}
<p>Get back to work.</p>
{% endif %}

{% if athlete_list and coach_list %}
Both athletes and coaches are available.
{% endif %}

{% if not athlete_list %}
There are no athletes.
{% endif %}

{% if athlete_list or coach_list %}
There are some athletes or some coaches.
{% endif %}

{% if not athlete_list or coach_list %}
There are no athletes or there are some coaches.
{% endif %}

{% if athlete_list and not coach_list %}
There are some athletes and absolutely no coaches.
{% endif %}

多条件
{% if athlete_list %}
{% if coach_list or cheerleader_list %}
We have athletes, and either coaches or cheerleaders!
{% endif %}
{% endif %}

for语句
{% for athlete in athlete_list %}
<h1>{{ athlete.name }}</h1>
<ul>
{% for sport in athlete.sports_played %}
<li>{{ sport }}</li>
{% endfor %}
</ul>
{% endfor %}

典型table
{% for country in countries %}
<table>
{% for city in country.city_list %}
<tr>
<td>Country #{{ forloop.parentloop.counter }}</td>
<td>City #{{ forloop.counter }}</td>
<td>{{ city }}</td>
</tr>
{% endfor %}
</table>
{% endfor %}

变量比较
{% ifequal user currentuser %}
<h1>Welcome!</h1>
{% endifequal %}

{% ifequal section 'sitenews' %}
<h1>Site News</h1>
{% endifequal %}

{% ifequal section "community" %}
<h1>Community</h1>
{% endifequal %}

注释
{# This is a comment #}

{% comment %}
This is a
multi-line comment.
{% endcomment %}

过滤
{{ name|lower }}

{{ my_list|first|upper }}

获取前30个词
{{ bio|truncatewords:"30" }}

格式化日期
{{ pub_date|date:"F j, Y" }}

设置模板的路径:setting.py
TEMPLATE_DIRS = (
'/home/django/mysite/templates',
)

动态模板路径
import os.path

TEMPLATE_DIRS = (
os.path.join(os.path.dirname(file), 'templates').replace('\','/'),
)

get_template动态加载模板
from django.template.loader import get_template
from django.template import Context
from django.http import HttpResponse
import datetime

def current_datetime(request):
now = datetime.datetime.now()
t = get_template('current_datetime.html')
html = t.render(Context({'current_date': now}))
return HttpResponse(html)

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})

内嵌模板:
{% include 'nav.html' %}
{% include "nav.html" %}

extends模板的用法
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<head>
<title>{% block title %}{% endblock %}</title>
</head>
<body>
<h1>My helpful timestamp site</h1>
{% block content %}{% endblock %}
{% block footer %}



<p>Thanks for visiting my site.</p>
{% endblock %}
</body>
</html>

{% extends "base.html" %}

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

{% block content %}
<p>It is now {{ current_date }}.</p>
{% endblock %}

{% extends "base.html" %}

{% block title %}Future time{% endblock %}

{% block content %}
<p>In {{ hour_offset }} hour(s), it will be {{ next_time }}.</p>
{% endblock %}

目录
相关文章
|
5月前
|
API 数据库 Python
Python 教程之 Django(8)在 Django 管理界面中渲染模型
Python 教程之 Django(8)在 Django 管理界面中渲染模型
43 0
Python 教程之 Django(8)在 Django 管理界面中渲染模型
|
2月前
|
前端开发 JavaScript 数据库
python Django教程 之模板渲染、循环、条件判断、常用的标签、过滤器
python Django教程 之模板渲染、循环、条件判断、常用的标签、过滤器
|
5月前
|
缓存 JavaScript 安全
Django的模板渲染(二)
Django的模板渲染(二)
|
5月前
|
前端开发 JavaScript 开发者
Django的模板渲染(一)
Django的模板渲染(一)
|
5月前
|
前端开发 JavaScript C++
【掰开揉碎】Django模板 vs 前端框架:选择合适的渲染方式
【掰开揉碎】Django模板 vs 前端框架:选择合适的渲染方式
145 7
|
5月前
|
开发者 Python
Django模板系统的强大之处:动态渲染与扩展性
【4月更文挑战第15天】Django模板系统是Web开发中的强大工具,支持动态渲染和扩展性。动态渲染包括变量、标签和过滤器的使用,实现内容根据上下文数据动态生成。模板继承和自定义标签则提升了扩展性,减少代码重复,增强可维护性。通过这些特性,Django模板系统助力开发者构建高效、动态的Web应用。
|
10月前
|
前端开发 API 数据库
Python 教程之 Django(8)在 Django 管理界面中渲染模型
Python 教程之 Django(8)在 Django 管理界面中渲染模型
40 0
|
2月前
|
机器学习/深度学习 数据采集 数据可视化
基于爬虫和机器学习的招聘数据分析与可视化系统,python django框架,前端bootstrap,机器学习有八种带有可视化大屏和后台
本文介绍了一个基于Python Django框架和Bootstrap前端技术,集成了机器学习算法和数据可视化的招聘数据分析与可视化系统,该系统通过爬虫技术获取职位信息,并使用多种机器学习模型进行薪资预测、职位匹配和趋势分析,提供了一个直观的可视化大屏和后台管理系统,以优化招聘策略并提升决策质量。
107 4
|
2月前
|
搜索推荐 前端开发 数据可视化
【优秀python web毕设案例】基于协同过滤算法的酒店推荐系统,django框架+bootstrap前端+echarts可视化,有后台有爬虫
本文介绍了一个基于Django框架、协同过滤算法、ECharts数据可视化以及Bootstrap前端技术的酒店推荐系统,该系统通过用户行为分析和推荐算法优化,提供个性化的酒店推荐和直观的数据展示,以提升用户体验。
101 1
|
16天前
|
机器学习/深度学习 人工智能 算法
植物病害识别系统Python+卷积神经网络算法+图像识别+人工智能项目+深度学习项目+计算机课设项目+Django网页界面
植物病害识别系统。本系统使用Python作为主要编程语言,通过收集水稻常见的四种叶片病害图片('细菌性叶枯病', '稻瘟病', '褐斑病', '稻瘟条纹病毒病')作为后面模型训练用到的数据集。然后使用TensorFlow搭建卷积神经网络算法模型,并进行多轮迭代训练,最后得到一个识别精度较高的算法模型,然后将其保存为h5格式的本地模型文件。再使用Django搭建Web网页平台操作界面,实现用户上传一张测试图片识别其名称。
68 21
植物病害识别系统Python+卷积神经网络算法+图像识别+人工智能项目+深度学习项目+计算机课设项目+Django网页界面