关于flask过滤器truncate源码分析

 

 

关于flask过滤器truncate源码分析

关于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,但这个可以在全局变量中重新配置。

代码部分:

关于flask过滤器truncate源码分析

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

关于flask过滤器truncate源码分析

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

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

关于flask过滤器truncate源码分析

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

关于flask过滤器truncate源码分析

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

关于flask过滤器truncate源码分析

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

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

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

 

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