django template实现定义临时变量,自定义赋值、自增实例
作者:djshichaoren 时间:2021-05-24 09:16:46
定义临时变量:
{% with i=1 %}
{{i}}
{% endwith %}
定义对临时变量操作的tag
在templatetags中创建set_val.py
内容是
from django import template
import logging
register = template.Library()
class SetVarNode(template.Node):
def __init__(self, var_name, var_value):
self.var_name = var_name
self.var_value = var_value
def render(self, context):
try:
value = template.Variable(self.var_value).resolve(context)
except template.VariableDoesNotExist:
value = ""
context[self.var_name] = value
return u""
class VarAddOneNode(template.Node):
def __init__(self, var_name):
self.var_name = var_name
def render(self, context):
try:
value = template.Variable(self.var_name).resolve(context)
context[self.var_name] = str( int(value) + 1 )
except template.VariableDoesNotExist:
value = ""
return u""
def set_var(parser, token):
"""
{% set <var_name> = <var_value> %}
"""
parts = token.split_contents()
logging.info('len(parts)=' + str(len(parts)))
if len(parts) == 2:
content = parts[1]
if content[len(content)-2 :len(content)] == '++':
var_name = content[:len(content) - 2]
return VarAddOneNode(var_name)
else:
return u""
elif len(parts) == 4:
return SetVarNode(parts[1], parts[3])
# raise template.TemplateSyntaxError("'set' tag must be of the form: {% set <var_name> = <var_value> %}")
register.tag('set', set_var)
然后在template中引入
{% load set_val %}
前端代码示例
{% load set_val %}
<div class="layui-form-item">
<div class="layui-form-label">商品尺码</div>
<div class="layui-input-block">
{% with i=1 %}
{% set i = 2 %}
{% for size in size_list %}
<div class="layui-col-md2">
<div class="layui-row">
原名:{{ size.sizeName }}
</div>
名字:
<input style="width: 40px;display:inline;" type="text" name="color" ,
lay-verify="required"
autocomplete="off" placeholder=""
class="layui-input" value={{ size.sizeName }}>
<br>
<input type="checkbox" name="size{{ i }}" lay-skin="primary" checked="checked">
{% set i++ %}
</div>
{% endfor %}
{% endwith %}
</div>
</div>
补充知识:django模板中做一些加减乘除基本运算
Django模版加法:
{{ value|add:10}} value=5,则返回15
Django模版减法:
{{value|add:-10}} value=5,则返回-5,这个比较好理解,减法就是加一个负数
Django模版乘法:
{% widthratio 5 1 100 %} 上面的代码表示:5/1 *100,返回500,widthratio需要三个参数,它会使用 参数1/参数2*参数3,所以要进行乘法的话,就将参数2=1即可
Django做除法,这里用到widthratio这个方法
<td>{% widthratio foo.product_amount 100 1 %}</td>#}
如果想将widthratio函数处理后的值当做变量,可以如下方法
{% widthratio this_value max_value max_width as width %}
{% blocktrans %}The width is: {{ width }}{% endblocktrans %}
数据保留两位小数
<td>{{ foo.product_amount |floatformat:5 }}</td>
register = template.Library()
一些复杂一些的运算
利用 add 这个filter ,可以做更疯狂的事:
计算 A^2: {% widthratio A 1 A %}
计算 (A+B)^2: {% widthratio A|add:B 1 A|add:B %}
计算 (A+B) * (C+D): {% widthratio A|add:B 1 C|add:D %}
除法并保留小数
首先定义方法在templatehelper.py文件中
@register.filter
def div(value, div):
'''
分转化为元,保留两位小数
:param value:
:param div:
:return:
'''
return round((value / div), 2)
然后在模板中可以按照如下使用,当然前提是{% load templatehelper %}:
<td>{{ foo.product_amount |div:100 }}</td>
尝试过一个笨办法,但是不生效,而且就算生效,也会出现忽略掉小数点后面得值的情况,所以不建议:
<td>{% widthratio foo.product_amount 100 1 as width %}{% blocktrans %}{{ width }}{% endblocktrans %}</td>#}
来源:https://blog.csdn.net/djshichaoren/article/details/78423554
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
用Python复现二战德军enigma密码机
![](https://img.aspxhome.com/file/2023/1/76191_0s.png)
通过python改变图片特定区域的颜色详解
![](https://img.aspxhome.com/file/2023/3/86543_0s.jpg)
详解Django中的ifequal和ifnotequal标签使用
python+pytest接口自动化之token关联登录的实现
![](https://img.aspxhome.com/file/2023/7/82707_0s.png)
Python脚本实现格式化css文件
js鼠标动画特效
![](https://img.aspxhome.com/file/UploadPic/20079/26/2007926183743348s.gif)
Django框架基础模板标签与filter使用方法详解
![](https://img.aspxhome.com/file/2023/5/66295_0s.png)
Js实现仿msn的右下角popup提示窗口
![](https://img.aspxhome.com/file/UploadPic/200712/27/20071227212229674s.gif)
驯服不听话的网页表格
ASP四级连动下拉列表程序段
python先序遍历二叉树问题
![](https://img.aspxhome.com/file/2023/7/82627_0s.png)
js断点调试经验分享
![](https://img.aspxhome.com/file/2023/7/55897_0s.png)
Python 实现图像合成微缩效果
![](https://img.aspxhome.com/file/2023/0/79440_0s.jpg)
php多任务程序实例解析
go 判断两个 slice/struct/map 是否相等的实例
python递归函数绘制分形树的方法
![](https://img.aspxhome.com/file/2023/9/67339_0s.jpg)
The Story of Mr.Gray — Web 交互设计“灰色”的8类应用
![](https://img.aspxhome.com/file/UploadPic/20101/11/mr-gray-01-93s.jpg)
前后端分离开发模式初体验
![](https://img.aspxhome.com/file/UploadPic/20096/24/devepro01-53s.jpg)
Python爬虫获取op.gg英雄联盟英雄对位胜率的源码
![](https://img.aspxhome.com/file/2023/3/83933_0s.png)