【问题标题】:Truncate a string in mako template截断 mako 模板中的字符串
【发布时间】:2011-04-24 12:05:03
【问题描述】:

如果标题太长,我想找到一种方法来截断标题,如下所示:

'this is a title'
'this is a very long title that ...'

有没有办法在 mako 中打印一个字符串,如果超过一定数量的字符,会自动用“...”截断?

谢谢。

【问题讨论】:

    标签: python pylons mako


    【解决方案1】:

    基本python解决方案:

    MAXLEN = 15
    def title_limit(title, limit):
        if len(title) > limit:
            title = title[:limit-3] + "..."
        return title
    
    blah = "blah blah blah blah blah"
    title_limit(blah) # returns 'blah blah bla...'
    

    这只会减少空格(如果可能的话)

    def find_rev(str,target,start):
        str = str[::-1]
        index = str.find(target,len(str) - start)
        if index != -1:
            index = len(str) - index
        return index
    
    def title_limit(title, limit):
        if len(title) <= limit: return title
        cut = find_rev(title, ' ', limit - 3 + 1)
        if cut != -1:
            title = title[:cut-1] + "..."
        else:
            title = title[:limit-3] + "..."
        return title
    
    print title_limit('The many Adventures of Bob', 10) # The...
    print title_limit('The many Adventures of Bob', 20) # The many...
    print title_limit('The many Adventures of Bob', 30) # The many Adventures of Bob
    

    【讨论】:

      【解决方案2】:

      webhelpers 与 MAKO 模板齐头并进。使用webhelpers.text.truncate - http://sluggo.scrapping.cc/python/WebHelpers/modules/text.html#webhelpers.text.truncate

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-02-07
        • 2019-12-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-29
        相关资源
        最近更新 更多