diff --git a/ckan/config/environment.py b/ckan/config/environment.py index eae1c4ededb..9112dd60c0f 100644 --- a/ckan/config/environment.py +++ b/ckan/config/environment.py @@ -305,6 +305,7 @@ def genshi_lookup_attr(cls, obj, key): env.install_gettext_callables(_, N_, newstyle=True) # custom filters env.filters['empty_and_escape'] = lib.jinja_tags.empty_and_escape + env.filters['truncate'] = lib.jinja_tags.truncate config['pylons.app_globals'].jinja_env = env # CONFIGURATION OPTIONS HERE (note: all config options will override diff --git a/ckan/lib/jinja_tags.py b/ckan/lib/jinja_tags.py index 821aa231804..161b91f9a83 100644 --- a/ckan/lib/jinja_tags.py +++ b/ckan/lib/jinja_tags.py @@ -5,6 +5,7 @@ from jinja2.ext import Extension from jinja2.exceptions import TemplateNotFound from jinja2.utils import open_if_exists, escape +from jinja2.filters import do_truncate import lib.base as base import lib.helpers as h @@ -19,6 +20,17 @@ def empty_and_escape(value): else: return escape(value) +def truncate(value, length=255, killwords=None, end='...'): + ''' A more clever truncate. If killwords is supplied we use the default + truncate. Otherwise we try to truncate using killwords=False, if this + truncates the whole value we try again with killwords=True ''' + if killwords is not None: + return do_truncate(value, length=length, killwords=killwords, end=end) + result = do_truncate(value, length=length, killwords=False, end=end) + if result != end: + return result + return do_truncate(value, length=length, killwords=True, end=end) + ### Tags class CkanExtend(Extension):