关于flask过滤器truncate源码分析

 

 

1.函数下面的注释:

逐句对照:

1.Return a truncated copy of the string。返回一个截断字符串的副本

2.The length is specified with the first parameter which defaults to ``255``.第一个参数默认指定的长度是'' 255 ''。

3.If the second parameter is ``true`` the filter will cut the text at length.如果第二个参数是“true”,过滤器按length长度切割文本

4. Otherwise it will discard the last word.否则他会丢弃最后一个单词

5.If the text was in fact truncated it will append an ellipsis sign (``"..."``).实际上如果文本截断它将附加一个省略符号(“…”)。

6.If you want a different ellipsis sign than ``"..."`` you can specify it using the third parameter.如果你想要一个不同于省略的符号”…”您可以指定使用第三个参数。

7.Strings that only exceed the length by the tolerance margin given in the fourth parameter will not be truncated.字符串的公差只有在超过第四个参数给的值才不会截断(第四个参数指leeway)

 

The default leeway on newer Jinja2 versions is 5 and was 0 before but can be reconfigured globally.默认的leeway 在Jinja2新版本是5,之前版本是0,但这个可以在全局变量中重新配置。

代码部分:

如果leeway 是None,那么leeway为环境中规定的默认值

断言:length必须 >= 3 ,否则提示后面的字符串“expected length >= %s,got %s”%(len(end),length)

断言:leeway 必须>=0, 否则提示后面的字符串 ‘expected leeway >= 0 ,got %s’%leeway

如果传入的字符串长度<= length+leeway,将字符串原样返回

如果killwords为True,返回字符串[:length-len(end)] +end(end默认是'...')

如果上述判断都不成立,就走到下面这个代码,result = 字符串[:length -len(end)](字符串切片).rsplit(" ",1)[0]

rsplit(" ",1)[0]表示从右往左分割字符串,以空格为分割标记,分割1次,分割后是个列表,取第0位元素的值。

返回 result + end (end默认就是'...')

 

个人理解,如有错误,请指出讨论,谢谢。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值