def truncate(string, length=255, killwords=False, end='...'):
    """Return a truncated copy of the string. The length is specified
    with the first parameter which defaults to ``255``. If the second
    parameter is ``true`` the filter will cut the text at length. Otherwise
    it will discard the last word. If the text was in fact
    truncated it will append an ellipsis sign (``"..."``). If you want a
    different ellipsis sign than ``"..."`` you can specify it using the
    third parameter.



    .. sourcecode::

    in views.py 

    context['my_string'] = 'foo bar baz'
       
    in template    
       
        &truncate($my_string,5)
          -> "foo ..."

        &truncate($my_string,5,killwords=True)
          -> "foo ba..."

    """
    if len(string) <= length:
        return string
    elif killwords:
        return string[:length - len(end)] + end
    result = string[:length - len(end)].rsplit(' ', 1)[0]
    if len(result) < length:
        result += ' '
    return result + end
