pythonDjango开发-自定义模板标签
1.在APP同级目录新建文件夹'templatetags' 并在文件夹下创建__init__.py和定义标签用的customer.py文件
2.在customer.py文件中定义自定义标签
from django import template from django.shortcuts import render,render_to_response import datetime register = template.Library() @register.simple_tag def get_current_time(format_string): return datetime.datetime.now().strftime(format_string) @register.simple_tag def get_html_test(): return '<div>123123123131<div/>'
3.在需要调用的html页面 调用 先需要在页面引入 自定义模板文件{% load customer %},然后调用
<!DOCTYPE html> {% load customer %} <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <link rel="icon" href="../../favicon.ico"> <title>中文BBS</title> <!-- Bootstrap core CSS --> <link href="../../static/css/bootstrap.min.css" rel="stylesheet"> <link href="../../static/css/customerize.css" rel="stylesheet"> <!-- Custom styles for this template --> <link href="../../static/css/navbar-static-top.css" rel="stylesheet"> </head> <body> {% get_current_time "%Y-%m-%d %I:%M %p" as the_time %} <p>The time is {{ the_time }}.</p> <div> {% get_html_test %} </div> <!-- Bootstrap core JavaScript ================================================== --> <!-- Placed at the end of the document so the pages load faster --> <script src="../../static/js/jquery.min.js"></script> <script src="../../static/js/bootstrap.min.js"></script> </body> </html>