网站建设运维,百度竞价推广后台,wordpress 激活邮件,网站建设的问题分析模板之变量
所有的数据类型都可以在模板中使用
render(request, index.html, context{})
render(request, index.html, contextlocals())
在模板中使用变量的时候#xff0c;用的是字典的key值#xff0c;key值value值一般保持一致详细…模板之变量
所有的数据类型都可以在模板中使用
render(request, index.html, context{})
render(request, index.html, contextlocals())
在模板中使用变量的时候用的是字典的key值key值value值一般保持一致详细请看上一篇末尾 模版之过滤器
语法 {{obj|filter__name:param}} 变量名字|过滤器名称变量类似于函数函数才可以传递参数 语法 {{ obj|过滤器:参数 }} 过滤器: default length filesizeformat date trancatechars slice safe mark_safe # 导入 default 如果一个变量是false或者为空使用给定的默认值。否则使用变量的值。例如 {{ value|default:nothing}}length 返回值的长度。它对字符串和列表都起作用。例如 {{ value|length }}如果 value 是 [‘a’, ‘b’, ‘c’, ‘d’]那么输出是 4。 filesizeformat 将值格式化为一个 “人类可读的” 文件尺寸 例如 13 KB, 4.1 MB, 102 bytes, 等等。例如 {{ value|filesizeformat }}如果 value 是 123456789输出将会是 117.7 MB。 date 如果 valuedatetime.datetime.now() {{ value|date:Y-m-d}}slice 如果 value”hello world” {{ value|slice:2:-1}}truncatechars 如果字符串字符多于指定的字符数量那么会被截断。截断的字符串将以可翻译的省略号序列“…”结尾。 参数要截断的字符数 例如 {{ value|truncatechars:9}}safe Django的模板中会对HTML标签和JS等语法标签进行自动转义原因显而易见这样是为了安全。但是有的时候我们可能不希望这些HTML元素被转义比如我们做一个内容管理系统后台添加的文章中是经过修饰的这些修饰可能是通过一个类似于FCKeditor编辑加注了HTML修饰符的文本如果自动转义的话显示的就是保护HTML标签的源文件。为了在Django中关闭HTML的自动转义有两种方式如果是一个单独的变量我们可以通过过滤器“|safe”的方式告诉Django这段代码是安全的不必转义。比如 valuea href点击/a{{ value|safe}}from django.utils.safestring import mark_safe
res mark_safe(h1HELLO WORLD/h1)
其它过滤器了解 过滤器 描述 示例 upper 以大写方式输出 add 给value加上一个数值 addslashes 单引号加上转义号 capfirst 第一个字母大写 center 输出指定长度的字符串把变量居中 cut 删除指定字符串 date 格式化日期 default 如果值不存在则使用默认值代替 default_if_none 如果值为None, 则使用默认值代替 dictsort 按某字段排序变量必须是一个dictionary dictsortreversed 按某字段倒序排序变量必须是dictionary divisibleby 判断是否可以被数字整除 escape 按HTML转义比如将””转换为”lt” filesizeformat 增加数字的可读性转换结果为13KB,89MB,3Bytes等 first 返回列表的第1个元素变量必须是一个列表 floatformat 转换为指定精度的小数默认保留1位小数 get_digit 从个位数开始截取指定位置的数字 join 用指定分隔符连接列表 length 返回列表中元素的个数或字符串长度 length_is 检查列表字符串长度是否符合指定的值 linebreaks 用 或 标签包裹变量 linebreaksbr 用 标签代替换行符 linenumbers 为变量中的每一行加上行号 ljust 输出指定长度的字符串变量左对齐 lower 字符串变小写 make_list 将字符串转换为列表 pluralize 根据数字确定是否输出英文复数符号 random 返回列表的随机一项 removetags 删除字符串中指定的HTML标记 rjust 输出指定长度的字符串变量右对齐 slice 切片操作 返回列表 slugify 在字符串中留下减号和下划线其它符号删除空格用减号替换 stringformat 字符串格式化语法同python time 返回日期的时间部分 timesince 以“到现在为止过了多长时间”显示时间变量 timeuntil 以“从现在开始到时间变量”还有多长时间显示时间变量 title 每个单词首字母大写 truncatewords 将字符串转换为省略表达方式 truncatewords_html 同上但保留其中的HTML标签 urlencode 将字符串中的特殊字符转换为url兼容表达方式 urlize 将变量字符串中的url由纯文本变为链接 wordcount 返回变量字符串中的单词数 模版之标签 标签看起来像是这样的 {% tag %} 标签比变量更加复杂一些在输出中创建文本一些通过循环或逻辑来控制流程一些加载其后的变量将使用到的额外信息到模版中。 一些标签需要开始和结束标签 例如{% tag %} ...标签 内容 ... {% endtag %} for标签
遍历每一个元素
{% for person in person_list %}p{{ person.name }}/p
{% endfor %}#可以利用{% for obj in list reversed %}反向完成循环。遍历一个字典
{% for key,val in dic.items %}p{{ key }}:{{ val }}/p
{% endfor %}{% for foo in d.keys %}p{{ foo }}/p
{% endfor %}{% for foo in d.values %}p{{ foo }}/p
{% endfor %}{% for foo in d.items %}p{{ foo }}/p
{% endfor %}
注循环序号可以通过forloop显示
forloop.counter The current iteration of the loop (1-indexed) 当前循环的索引值从1开始
forloop.counter0 The current iteration of the loop (0-indexed) 当前循环的索引值从0开始
forloop.revcounter The number of iterations from the end of the loop (1-indexed) 当前循环的倒序索引值从1开始
forloop.revcounter0 The number of iterations from the end of the loop (0-indexed) 当前循环的倒序索引值从0开始
forloop.first True if this is the first time through the loop 当前循环是不是第一次循环布尔值
forloop.last True if this is the last time through the loop 当前循环是不是最后一次循环布尔值
forloop.parentloop 本层循环的外层循环
for … empty
# for 标签带有一个可选的{% empty %} 从句以便在给出的组是空的或者没有被找到时可以有所操作。
{% for person in person_list %}p{{ person.name }}/p{% empty %}psorry,no person here/p
{% endfor %}
if 标签
# {% if %}会对一个变量求值如果它的值是True存在、不为空、且不是boolean类型的false值对应的内容块会输出。{% if num 100 or num 0 %}p无效/p
{% elif num 80 and num 100 %}p优秀/p
{% else %}p凑活吧/p
{% endif %}if语句支持 and 、or、、、、!、、、in、not in、is、is not判断。
with 使用一个简单地名字缓存一个复杂的变量当你需要使用一个“昂贵的”方法比如访问数据库很多次的时候是非常有用的 例如
d {username:kevin,age:18,info:这个人有点意思,hobby:[111,222,333,{info:NB}]}# with起别名
{% with d.hobby.3.info as nb %}p{{ nb }}/p在with语法内就可以通过as后面的别名快速的使用到前面非常复杂获取数据的方式p{{ d.hobby.3.info }}/p
{% endwith %}{% with totalbusiness.employees.count %}{{ total }} employee{{ total|pluralize }}
{% endwith %}
不要写成as
csrf_token
{% csrf_token%}这个标签用于跨站请求伪造保护 模版导入和继承
模版导入 语法{% include 模版名称 %}如{% include adv.html %}基本代码示例 div classadvdiv classpanel panel-defaultdiv classpanel-headingh3 classpanel-titlePanel title/h3/divdiv classpanel-bodyPanel content/div/divdiv classpanel panel-dangerdiv classpanel-headingh3 classpanel-titlePanel title/h3/divdiv classpanel-bodyPanel content/div/divdiv classpanel panel-warningdiv classpanel-headingh3 classpanel-titlePanel title/h3/divdiv classpanel-bodyPanel content/div/div
/div !DOCTYPE html
html langen
headmeta charsetUTF-8titleTitle/titlelink relstylesheet href/static/bootstrap-3.3.7-dist/css/bootstrap.min.css{# link relstylesheet hrefhttps://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css integritysha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4VaPmSTsz/K68vbdEjh4u crossoriginanonymous#}style* {margin: 0;padding: 0;}.header {height: 50px;width: 100%;background-color: #369;}/style
/head
body
div classheader/divdiv classcontainerdiv classrowdiv classcol-md-3{% include adv.html %}/divdiv classcol-md-9{% block conn %}h1你好/h1{% endblock %}/div/div/div/body
/html{% extends base.html %}{% block conn %}{{ block.super }}
是啊{% endblock conn%}模版继承 Django模版引擎中最强大也是最复杂的部分就是模版继承了。模版继承可以让您创建一个基本的“骨架”模版它包含您站点中的全部元素并且可以定义能够被子模版覆盖的 blocks 。 通过从下面这个例子开始可以容易的理解模版继承 !DOCTYPE html
html langen
headlink relstylesheet hrefstyle.css/title{% block title %}My amazing site{% endblock %}/title
/headbody
div idsidebar{% block sidebar %}ullia href/Home/a/lilia href/blog/Blog/a/li/ul{% endblock %}
/divdiv idcontent{% block content %}{% endblock %}
/div
/body
/html 这个模版我们把它叫作 base.html 它定义了一个可以用于两列排版页面的简单HTML骨架。“子模版”的工作是用它们的内容填充空的blocks。 在这个例子中 block 标签定义了三个可以被子模版内容填充的block。 block 告诉模版引擎 子模版可能会覆盖掉模版中的这些位置。 子模版可能看起来是这样的 {% extends base.html %}{% block title %}My amazing blog{% endblock %}{% block content %}
{% for entry in blog_entries %}h2{{ entry.title }}/h2p{{ entry.body }}/p
{% endfor %}
{% endblock %} extends 标签是这里的关键。它告诉模版引擎这个模版“继承”了另一个模版。当模版系统处理这个模版时首先它将定位父模版——在此例中就是“base.html”。 那时模版引擎将注意到 base.html 中的三个 block 标签并用子模版中的内容来替换这些block。根据 blog_entries 的值输出可能看起来是这样的 !DOCTYPE html
html langen
headlink relstylesheet hrefstyle.css /titleMy amazing blog/title
/headbodydiv idsidebarullia href/Home/a/lilia href/blog/Blog/a/li/ul/divdiv idcontenth2Entry one/h2pThis is my first entry./ph2Entry two/h2pThis is my second entry./p/div
/body
/html 请注意子模版并没有定义 sidebar block所以系统使用了父模版中的值。父模版的 {% block %} 标签中的内容总是被用作备选内容fallback。 这种方式使代码得到最大程度的复用并且使得添加内容到共享的内容区域更加简单例如部分范围内的导航。 **这里是使用继承的一些提示** 如果你在模版中使用 {% extends %} 标签它必须是模版中的第一个标签。其他的任何情况下模版继承都将无法工作。 在base模版中设置越多的 {% block %} 标签越好。请记住子模版不必定义全部父模版中的blocks所以你可以在大多数blocks中填充合理的默认内容然后只定义你需要的那一个。多一点钩子总比少一点好。 如果你发现你自己在大量的模版中复制内容那可能意味着你应该把内容移动到父模版中的一个 {% block %} 中。 If you need to get the content of the block from the parent template, the {{ block.super }} variable will do the trick. This is useful if you want to add to the contents of a parent block instead of completely overriding it. Data inserted using {{ block.super }} will not be automatically escaped (see the next section), since it was already escaped, if necessary, in the parent template. 为了更好的可读性你也可以给你的 {% endblock %} 标签一个 *名字* 。例如 {%block content %}...{%endblock content %} 在大型模版中这个方法帮你清楚的看到哪一个 {% block %} 标签被关闭了。 不能在一个模版中定义多个相同名字的 block 标签。 实战代码实例 在Bootstrap中文网获取模块 、 导航条 巨幕 缩略图 views.py模块 def home(request):return render(request,home.html)def login(request):return render(request,login.html)def register(request):return render(request,register.html)urls.py模块 from django.conf.urls import url
from django.contrib import admin
from app01 import viewsurlpatterns [url(r^admin/, admin.site.urls),url(r^index/,views.index),url(r^home/,views.home),url(r^login/,views.login),url(r^register/,views.register),]templates\home.html模块 !DOCTYPE html
html langen
headmeta charsetUTF-8titleTitle/titlescript srchttps://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.min.js/scriptlink hrefhttps://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css relstylesheetscript srchttps://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js/script{% block css %}{% endblock %}/head
body
nav classnavbar navbar-defaultdiv classcontainer-fluid!-- Brand and toggle get grouped for better mobile display --div classnavbar-headerbutton typebutton classnavbar-toggle collapsed data-togglecollapsedata-target#bs-example-navbar-collapse-1 aria-expandedfalsespan classsr-onlyToggle navigation/spanspan classicon-bar/spanspan classicon-bar/spanspan classicon-bar/span/buttona classnavbar-brand href#《遮天》/a/div!-- Collect the nav links, forms, and other content for toggling --div classcollapse navbar-collapse idbs-example-navbar-collapse-1ul classnav navbar-navli classactivea href#荒古圣体span classsr-only(current)/span/a/lilia href#极尽升华/a/lili classdropdowna href# classdropdown-toggle data-toggledropdown rolebutton aria-haspopuptruearia-expandedfalse极道帝兵span classcaret/span/aul classdropdown-menulia href#荒塔/a/lilia href#仙钟/a/lilia href#吞天魔罐/a/lili roleseparator classdivider/lilia href#青莲帝兵/a/lili roleseparator classdivider/lilia href#仙铁棍/a/li/ul/li/ulform classnavbar-form navbar-leftdiv classform-groupinput typetext classform-control placeholderSearch/divbutton typesubmit classbtn btn-defaultSubmit/button/formul classnav navbar-nav navbar-rightlia href#Link/a/lili classdropdowna href# classdropdown-toggle data-toggledropdown rolebutton aria-haspopuptruearia-expandedfalseDropdown span classcaret/span/aul classdropdown-menulia href#Action/a/lilia href#Another action/a/lilia href#Something else here/a/lili roleseparator classdivider/lilia href#Separated link/a/li/ul/li/ul/div!-- /.navbar-collapse --/div!-- /.container-fluid --
/navdiv classcontainer-fluiddiv classrowdiv classcol-md-3div classlist-group{% block ft %}div classlist-groupa href/home/ classlist-group-item active欢迎来到仙侠世界/aa href/login/ classlist-group-item登陆星空古路/aa href/register/ classlist-group-item加入圣地考核/aa href# classlist-group-item修仙技术支持/aa href# classlist-group-item更多/a/div{% endblock %}/div/divdiv classcol-md-9div classpanel panel-infodiv classpanel-heading九秘/div{% block content %}div classpanel-bodydiv classjumbotronh1少年你想变强吗/h1p加入我们/ppa classbtn btn-primary btn-lg href# rolebutton快来快来/a/p/divdiv classrowdiv classcol-sm-6 col-md-4div classthumbnailimg srchttps://img1.baidu.com/it/u803199455,778449086fm253fmtautoapp120fJPEG?w800h1080alt...div classcaptionh3Thumbnail label/h3p.../ppa href# classbtn btn-primary rolebuttonButton/a a href#classbtn btn-defaultrolebuttonButton/a/p/div/div/divdiv classcol-sm-6 col-md-4div classthumbnailimg srchttps://img1.baidu.com/it/u3707885883,1615845000fm253fmtautoapp120fJPEG?w640h337alt...div classcaptionh3Thumbnail label/h3p.../ppa href# classbtn btn-primary rolebuttonButton/a a href#classbtn btn-defaultrolebuttonButton/a/p/div/div/divdiv classcol-sm-6 col-md-4div classthumbnailimg srchttps://img1.baidu.com/it/u1395000385,3610786620fm253fmtautoapp120fJPEG?w889h500alt...div classcaptionh3Thumbnail label/h3p.../ppa href# classbtn btn-primary rolebuttonButton/a a href#classbtn btn-defaultrolebuttonButton/a/p/div/div/div/div/div{% endblock %}/div/div/div
/div
{% block js %}{% endblock %}/body
/htmllogin.html模块 {% extends home.html %}{% block css %}styleh1{color:red;}/style
{% endblock %}{% block ft %}div classlist-groupa href/home/ classlist-group-item active欢迎来到仙侠世界/aa href/login/ classlist-group-item登陆星空古路/aa href/register/ classlist-group-item加入圣地考核/a/div
{% endblock %}{% block content %}h1 classtext-center登陆页面/h1div classrowdiv classcol-md-8 col-md-offset-2form actiondiv classform-group用户名input typetext classform-control/divdiv classform-group密码input typetext classform-control/divdiv classform-groupinput typesubmit classbtn btn-success btn-block value提交/div/form{% include hahah.html %}/div/div
{% endblock %}{% block js %}scriptalert(login)/script
{% endblock %} register.html 模块 {% extends home.html %}
{% block ft %}div classlist-groupa href/home/ classlist-group-item active欢迎来到仙侠世界/aa href/login/ classlist-group-item登陆星空古路/aa href/register/ classlist-group-item加入圣地考核/a/div
{% endblock %}{% block content %}h1 classtext-center注册页面/h1div classrowdiv classcol-md-8 col-md-offset-2form actiondiv classform-group用户名input typetext classform-control/divdiv classform-group密码input typetext classform-control/divdiv classform-groupinput typesubmit classbtn btn-success btn-block value提交/div/form/div/div
{% endblock %}{% block js %}scriptalert(register)/script
{% endblock %} END
文章转载自: http://www.morning.tnzwm.cn.gov.cn.tnzwm.cn http://www.morning.plqkz.cn.gov.cn.plqkz.cn http://www.morning.kpmxn.cn.gov.cn.kpmxn.cn http://www.morning.alwpc.cn.gov.cn.alwpc.cn http://www.morning.hmxb.cn.gov.cn.hmxb.cn http://www.morning.pcgjj.cn.gov.cn.pcgjj.cn http://www.morning.qcbhb.cn.gov.cn.qcbhb.cn http://www.morning.kjlia.com.gov.cn.kjlia.com http://www.morning.ncrk.cn.gov.cn.ncrk.cn http://www.morning.yrrnx.cn.gov.cn.yrrnx.cn http://www.morning.skkln.cn.gov.cn.skkln.cn http://www.morning.hlrtzcj.cn.gov.cn.hlrtzcj.cn http://www.morning.bpmnh.cn.gov.cn.bpmnh.cn http://www.morning.gyzfp.cn.gov.cn.gyzfp.cn http://www.morning.wxrbl.cn.gov.cn.wxrbl.cn http://www.morning.qjlnh.cn.gov.cn.qjlnh.cn http://www.morning.qngcq.cn.gov.cn.qngcq.cn http://www.morning.klyyd.cn.gov.cn.klyyd.cn http://www.morning.clndl.cn.gov.cn.clndl.cn http://www.morning.frxsl.cn.gov.cn.frxsl.cn http://www.morning.ykbgs.cn.gov.cn.ykbgs.cn http://www.morning.hsflq.cn.gov.cn.hsflq.cn http://www.morning.newfeiya.com.cn.gov.cn.newfeiya.com.cn http://www.morning.blbys.cn.gov.cn.blbys.cn http://www.morning.bpmtj.cn.gov.cn.bpmtj.cn http://www.morning.xwlmg.cn.gov.cn.xwlmg.cn http://www.morning.qgzmz.cn.gov.cn.qgzmz.cn http://www.morning.zymgs.cn.gov.cn.zymgs.cn http://www.morning.fnywn.cn.gov.cn.fnywn.cn http://www.morning.qtzk.cn.gov.cn.qtzk.cn http://www.morning.sjwzl.cn.gov.cn.sjwzl.cn http://www.morning.cwlxs.cn.gov.cn.cwlxs.cn http://www.morning.kjksn.cn.gov.cn.kjksn.cn http://www.morning.dhtdl.cn.gov.cn.dhtdl.cn http://www.morning.fqlxg.cn.gov.cn.fqlxg.cn http://www.morning.zrrgx.cn.gov.cn.zrrgx.cn http://www.morning.msgrq.cn.gov.cn.msgrq.cn http://www.morning.kwqqs.cn.gov.cn.kwqqs.cn http://www.morning.rnqyy.cn.gov.cn.rnqyy.cn http://www.morning.xysxj.com.gov.cn.xysxj.com http://www.morning.807yy.cn.gov.cn.807yy.cn http://www.morning.wdpbq.cn.gov.cn.wdpbq.cn http://www.morning.kwjyt.cn.gov.cn.kwjyt.cn http://www.morning.rxfgh.cn.gov.cn.rxfgh.cn http://www.morning.rqqkc.cn.gov.cn.rqqkc.cn http://www.morning.pamdeer.com.gov.cn.pamdeer.com http://www.morning.wdqhg.cn.gov.cn.wdqhg.cn http://www.morning.cwqrj.cn.gov.cn.cwqrj.cn http://www.morning.dztp.cn.gov.cn.dztp.cn http://www.morning.bpmfz.cn.gov.cn.bpmfz.cn http://www.morning.dmhs.cn.gov.cn.dmhs.cn http://www.morning.zcckq.cn.gov.cn.zcckq.cn http://www.morning.mxcgf.cn.gov.cn.mxcgf.cn http://www.morning.fbfnk.cn.gov.cn.fbfnk.cn http://www.morning.rfyk.cn.gov.cn.rfyk.cn http://www.morning.wzwyz.cn.gov.cn.wzwyz.cn http://www.morning.qydgk.cn.gov.cn.qydgk.cn http://www.morning.sqqhd.cn.gov.cn.sqqhd.cn http://www.morning.wcghr.cn.gov.cn.wcghr.cn http://www.morning.jmbfx.cn.gov.cn.jmbfx.cn http://www.morning.rxyz.cn.gov.cn.rxyz.cn http://www.morning.dnqlba.cn.gov.cn.dnqlba.cn http://www.morning.rkjb.cn.gov.cn.rkjb.cn http://www.morning.c7622.cn.gov.cn.c7622.cn http://www.morning.qpnb.cn.gov.cn.qpnb.cn http://www.morning.lmfxq.cn.gov.cn.lmfxq.cn http://www.morning.caswellintl.com.gov.cn.caswellintl.com http://www.morning.flzqq.cn.gov.cn.flzqq.cn http://www.morning.qcwrm.cn.gov.cn.qcwrm.cn http://www.morning.cgbgc.cn.gov.cn.cgbgc.cn http://www.morning.bxrqf.cn.gov.cn.bxrqf.cn http://www.morning.clzly.cn.gov.cn.clzly.cn http://www.morning.lxfdh.cn.gov.cn.lxfdh.cn http://www.morning.kdpal.cn.gov.cn.kdpal.cn http://www.morning.shxrn.cn.gov.cn.shxrn.cn http://www.morning.wjyyg.cn.gov.cn.wjyyg.cn http://www.morning.gbcnz.cn.gov.cn.gbcnz.cn http://www.morning.xtqr.cn.gov.cn.xtqr.cn http://www.morning.sdhmn.cn.gov.cn.sdhmn.cn http://www.morning.xpqdf.cn.gov.cn.xpqdf.cn