一、模板路径配置
1.在项目中创建templates文件夹存放模板文件
2.修改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',
],
},
},
]
3.使用模板文件
defshow_article(request):
articles={}
article_list=[]for i in range(30):
dt= datetime.datetime.now() - datetime.timedelta(days=random.randint(0, 100))
article_list.append((dt,"python 函数返回多个值"))
article_list= sorted(article_list, key=lambdaele: ele[0])
article_list.reverse()for article inarticle_list:
d= article[0].strftime("%Y-%m")if notarticles.get(d, None):
articles[d]=[]
articles[d].append(article)return render(request, 'article/show-article.html', context={"articles": articles})
上述代码中的模板路径表示在templates目录下存在article目录下的show-article.html文件,一般会在templates下创建与每个应用名相同的文件夹,用于存放该应用的模板。
4.模板配置的两种方式
第一种:DIRS 定义一个目录列表,模板引擎按列表顺序搜索这些目录以查找模板源文件,将templates放在主项目目录下。
前3步使用了第一种方式,这种方式是常用方式。
第二种:APP_DIRS告诉模板引擎是否应该进入每个已安装的应用中查找模板,值为True则模板会去安装了的app下面的templates文件夹查找模板,所以我们也可以在每个app的里面创建模板目录templates存放模板,这种方式需要将这个app添加到setting.py文件的INSTALLED_APPS列表中。
二、模板变量
1.使用规则
语法: { { 变量名 }};
命名由字母和数字以及下划线组成,不能有空格和标点符号;
可以使用字典、模型、方法、函数、列表,方法和函数不能带括号&#x