Django实战(二)之模板语言
该实战教程基于菜鸟教程,菜鸟教程可参考:http://www.runoob.com/django/django-template.html 模板语法,每个框架都有其支持的模板语法,Django的模板语法在我看来与vue.js倒有一些相似处 ,比如它们的模板语法中参数为{{parm}}。 本篇所用到的例子,仍然基于实战(一) 在HelloWorld(该文件夹有urls.py)目录下新增templates文件夹,在templates新增hello.html <html> head</bodyh1>{{ hello }}> ? 修改settings.py文件夹 TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates','DIRS': [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',},]
这个修改位置就好比Java的SSM开发中的视图解析器(可以是freemarker,可以是jsp,也可以是volocity等)。 ? 修改view.py # -*- coding: utf-8 -*-
#from django.http import HttpResponse
from django.shortcuts import render
def hello(request):
context = {}
context['hello'] = 'Hello World!'
return render(request,'hello.html',context)
这里的context与Java中的Map或者是Model倒也几分相似。 简单的说,都是来返回给前端数据渲染用的。 ? 最后显示为: ? ? 这里说一下Django的模板语言 编程语言什么if-else,if-else if -else,for 等等是十分比较常用的。 而Django作为Python的web框架同样如此。 ? ?? (1)if/else或if/elseif/else标签 {% if condition %} ... display {% endif %} {% if condition1 %} ... display 1 {% elif condition2 %} ... display 2 {% else %} ... display 3 {% endif %} <ul>
{% for athlete in athlete_list %}
<li>{{ athlete.name }}</li>
{% endfor %}
</ul>
{% ifequal %} 标签比较两个值,当他们相等时,显示在 {% ifequal %} 和 {% endifequal %} 之中所有的值。 下面的例子比较两个模板变量 user 和 currentuser : ? {% ifequal user currentuser %} <h1>Welcome!</h1> {% endifequal %} {% ifequal section 'sitenews' %} <h1>Site News</h1> {% else %} <h1>No News Here</h1> {% endifequal %} {# 这是一个注释 #} {{ name|lower }} {{ name }} 变量被过滤器 lower 处理后,文档大写转换文本为小写。 过滤管道可以被* 套接* ,既是说,一个过滤器管道的输出又可以作为下一个管道的输入 ? ? (6)include 标签 {% include "nav.html" %} ? (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |