Template helper functions reference

Helper functions

Consists of functions to typically be used within templates, but also available to Controllers. This module is available to templates as ‘h’.

class ckan.lib.helpers.HelperAttributeDict(*args, **kwargs)
class ckan.lib.helpers.literal

Represents an HTML literal.

classmethod escape(s)

Escape a string. Calls escape() and ensures that for subclasses the correct type is returned.

ckan.lib.helpers.core_helper(f, name=None)

Register a function as a builtin helper method.

ckan.lib.helpers.redirect_to(*args, **kw)

Issue a redirect: return an HTTP response with a 302 Moved header.

This is a wrapper for routes.redirect_to() that maintains the user’s selected language when redirecting.

The arguments to this function identify the route to redirect to, they’re the same arguments as ckan.plugins.toolkit.url_for() accepts, for example:

import ckan.plugins.toolkit as toolkit

# Redirect to /dataset/my_dataset.
toolkit.redirect_to('dataset.read',
                    id='my_dataset')

Or, using a named route:

toolkit.redirect_to('dataset.read', id='changed')

If given a single string as argument, this redirects without url parsing

toolkit.redirect_to(‘http://example.com’) toolkit.redirect_to(‘/dataset’) toolkit.redirect_to(‘/some/other/path’)
ckan.lib.helpers.url(*args, **kw)

Deprecated: please use url_for instead

ckan.lib.helpers.get_site_protocol_and_host()

Return the protocol and host of the configured ckan.site_url. This is needed to generate valid, full-qualified URLs.

If ckan.site_url is set like this:

ckan.site_url = http://example.com

Then this function would return a tuple (‘http’, ‘example.com’) If the setting is missing, (None, None) is returned instead.

ckan.lib.helpers.url_for(*args, **kw)

Return the URL for an endpoint given some parameters.

This is a wrapper for flask.url_for() and routes.url_for() that adds some extra features that CKAN needs.

To build a URL for a Flask view, pass the name of the blueprint and the view function separated by a period ., plus any URL parameters:

url_for('api.action', ver=3, logic_function='status_show')
# Returns /api/3/action/status_show

For a fully qualified URL pass the _external=True parameter. This takes the ckan.site_url and ckan.root_path settings into account:

url_for('api.action', ver=3, logic_function='status_show',
        _external=True)
# Returns http://example.com/api/3/action/status_show

URLs built by Pylons use the Routes syntax:

url_for(controller='my_ctrl', action='my_action', id='my_dataset')
# Returns '/dataset/my_dataset'

Or, using a named route:

url_for('dataset.read', id='changed')
# Returns '/dataset/changed'

Use qualified=True for a fully qualified URL when targeting a Pylons endpoint.

For backwards compatibility, an effort is made to support the Pylons syntax when building a Flask URL, but this support might be dropped in the future, so calls should be updated.

ckan.lib.helpers.url_for_static(*args, **kw)

Returns the URL for static content that doesn’t get translated (eg CSS)

It’ll raise CkanUrlException if called with an external URL

This is a wrapper for routes.url_for()

ckan.lib.helpers.url_for_static_or_external(*args, **kw)

Returns the URL for static content that doesn’t get translated (eg CSS), or external URLs

ckan.lib.helpers.is_url(*args, **kw)

Returns True if argument parses as a http, https or ftp URL

ckan.lib.helpers.url_is_local(url)

Returns True if url is local

ckan.lib.helpers.full_current_url()

Returns the fully qualified current url (eg http://…) useful for sharing etc

ckan.lib.helpers.current_url()

Returns current url unquoted

ckan.lib.helpers.lang()

Return the language code for the current locale eg en

ckan.lib.helpers.ckan_version()

Return CKAN version

ckan.lib.helpers.lang_native_name(lang=None)

Return the language name currently used in it’s localised form either from parameter or current environ setting

ckan.lib.helpers.is_rtl_language()
ckan.lib.helpers.get_rtl_theme()
ckan.lib.helpers.get_rtl_css()
class ckan.lib.helpers.Message(category, message, allow_html)

A message returned by Flash.pop_messages().

Converting the message to a string returns the message text. Instances also have the following attributes:

  • message: the message text.
  • category: the category specified when the message was created.
ckan.lib.helpers.flash_notice(message, allow_html=False)

Show a flash message of type notice

ckan.lib.helpers.flash_error(message, allow_html=False)

Show a flash message of type error

ckan.lib.helpers.flash_success(message, allow_html=False)

Show a flash message of type success

ckan.lib.helpers.are_there_flash_messages()

Returns True if there are flash messages for the current user

ckan.lib.helpers.file(name, value=None, id=None, **attrs)

Create a file upload field.

If you are using file uploads then you will also need to set the multipart option for the form.

Example:

>>> file('myfile')
literal(u'<input id="myfile" name="myfile" type="file" />')
ckan.lib.helpers.submit(name, value=None, id=None, **attrs)

Create a submit field.

Parameters:
  • class – pass extra class(es) to add to the <a> tag
  • icon – name of ckan icon to use within the link
  • condition – if False then no link is returned

Create a link for a named route. Deprecated in ckan 2.0

Create a link for a named route. Deprecated in ckan 2.0

ckan.lib.helpers.subnav_named_route(text, named_route, **kwargs)

Generate a subnav element based on a named route Deprecated in ckan 2.0

ckan.lib.helpers.build_nav_main(*args)

build a set of menu items.

args: tuples of (menu type, title) eg (‘login’, _(‘Login’)) outputs <li><a href=”…”>title</a></li>

ckan.lib.helpers.build_nav_icon(menu_item, title, **kw)

Build a navigation item used for example in user/read_base.html.

Outputs <li><a href="..."><i class="icon.."></i> title</a></li>.

Parameters:
  • menu_item (string) – the name of the defined menu item defined in config/routing as the named route of the same name
  • title (string) – text used for the link
  • kw – additional keywords needed for creating url eg id=...
Return type:

HTML literal

ckan.lib.helpers.build_nav(menu_item, title, **kw)

Build a navigation item used for example breadcrumbs.

Outputs <li><a href="...">title</a></li>.

Parameters:
  • menu_item (string) – the name of the defined menu item defined in config/routing as the named route of the same name
  • title (string) – text used for the link
  • kw – additional keywords needed for creating url eg id=...
Return type:

HTML literal

ckan.lib.helpers.map_pylons_to_flask_route_name(menu_item)

returns flask routes for old fashioned route names

ckan.lib.helpers.build_extra_admin_nav()

Build extra navigation items used in admin/base.html for values defined in the config option ckan.admin_tabs. Typically this is populated by extensions.

Return type:HTML literal
ckan.lib.helpers.default_group_type()
ckan.lib.helpers.get_facet_items_dict(facet, search_facets=None, limit=None, exclude_active=False)

Return the list of unselected facet items for the given facet, sorted by count.

Returns the list of unselected facet contraints or facet items (e.g. tag names like “russian” or “tolstoy”) for the given search facet (e.g. “tags”), sorted by facet item count (i.e. the number of search results that match each facet item).

Reads the complete list of facet items for the given facet from c.search_facets, and filters out the facet items that the user has already selected.

Arguments: facet – the name of the facet to filter. search_facets – dict with search facets(c.search_facets in Pylons) limit – the max. number of facet items to return. exclude_active – only return unselected facets.

ckan.lib.helpers.has_more_facets(facet, search_facets, limit=None, exclude_active=False)

Returns True if there are more facet items for the given facet than the limit.

Reads the complete list of facet items for the given facet from c.search_facets, and filters out the facet items that the user has already selected.

Arguments: facet – the name of the facet to filter. search_facets – dict with search facets(c.search_facets in Pylons) limit – the max. number of facet items. exclude_active – only return unselected facets.

ckan.lib.helpers.unselected_facet_items(facet, limit=10)

Return the list of unselected facet items for the given facet, sorted by count.

Returns the list of unselected facet contraints or facet items (e.g. tag names like “russian” or “tolstoy”) for the given search facet (e.g. “tags”), sorted by facet item count (i.e. the number of search results that match each facet item).

Reads the complete list of facet items for the given facet from c.search_facets, and filters out the facet items that the user has already selected.

Arguments: facet – the name of the facet to filter. limit – the max. number of facet items to return.

ckan.lib.helpers.get_facet_title(name)

Deprecated in ckan 2.0

ckan.lib.helpers.get_param_int(name, default=10)
ckan.lib.helpers.sorted_extras(package_extras, auto_clean=False, subs=None, exclude=None)

Used for outputting package extras

Parameters:
  • package_extras (dict) – the package extras
  • auto_clean (bool) – If true capitalize and replace -_ with spaces
  • subs (dict {'key': 'replacement'}) – substitutes to use instead of given keys
  • exclude (list of strings) – keys to exclude
ckan.lib.helpers.check_access(action, data_dict=None)
ckan.lib.helpers.get_action(action_name, data_dict=None)

Calls an action function from a template. Deprecated in CKAN 2.3.

ckan.lib.helpers.linked_user(user, maxlength=0, avatar=20)
ckan.lib.helpers.group_name_to_title(name)
ckan.lib.helpers.truncate(text, length=30, indicator='...', whole_word=False)

Truncate text with replacement characters.

length
The maximum length of text before replacement
indicator
If text exceeds the length, this string will replace the end of the string
whole_word
If true, shorten the string further to avoid breaking a word in the middle. A word is defined as any string not containing whitespace. If the entire text before the break is a single word, it will have to be broken.

Example:

>>> truncate('Once upon a time in a world far far away', 14)
'Once upon a...'

TODO: try to replace it with built-in textwrap.shorten (available starting from Python 3.4) when support for Python 2 completely dropped.

ckan.lib.helpers.markdown_extract(text, extract_length=190)

return the plain text representation of markdown encoded text. That is the texted without any html tags. If extract_length is 0 then it will not be truncated.

ckan.lib.helpers.icon_url(name)
ckan.lib.helpers.icon_html(url, alt=None, inline=True)
ckan.lib.helpers.icon(name, alt=None, inline=True)
ckan.lib.helpers.resource_icon(res)
ckan.lib.helpers.format_icon(_format)
ckan.lib.helpers.dict_list_reduce(list_, key, unique=True)

Take a list of dicts and create a new one containing just the values for the key with unique values if requested.

ckan.lib.helpers.gravatar(email_hash, size=100, default=None)
ckan.lib.helpers.sanitize_url(url)

Return a sanitized version of a user-provided url for use in an <a href> or <img src> attribute, e.g.:

<a href=”{{ h.sanitize_url(user_link) }}”>

Sanitizing urls is tricky. This is a best-effort to produce something valid from the sort of text users might paste into a web form, not intended to cover all possible valid edge-case urls.

On parsing errors an empty string will be returned.

ckan.lib.helpers.user_image(user_id, size=100)
ckan.lib.helpers.pager_url(page, partial=None, **kwargs)
ckan.lib.helpers.get_page_number(params, key='page', default=1)

Return the page number from the provided params after verifying that it is an positive integer.

If it fails it will abort the request with a 400 error.

ckan.lib.helpers.get_display_timezone()

Returns a pytz timezone for the display_timezone setting in the configuration file or UTC if not specified. :rtype: timezone

ckan.lib.helpers.render_datetime(datetime_, date_format=None, with_hours=False, with_seconds=False)

Render a datetime object or timestamp string as a localised date or in the requested format. If timestamp is badly formatted, then a blank string is returned.

Parameters:
  • datetime (datetime or ISO string format) – the date
  • date_format (string) – a date format
  • with_hours (bool) – should the hours:mins be shown
  • with_seconds (bool) – should the hours:mins:seconds be shown
Return type:

string

ckan.lib.helpers.date_str_to_datetime(date_str)

Convert ISO-like formatted datestring to datetime object.

This function converts ISO format date- and datetime-strings into datetime objects. Times may be specified down to the microsecond. UTC offset or timezone information may not be included in the string.

Note - Although originally documented as parsing ISO date(-times), this
function doesn’t fully adhere to the format. This function will throw a ValueError if the string contains UTC offset information. So in that sense, it is less liberal than ISO format. On the other hand, it is more liberal of the accepted delimiters between the values in the string. Also, it allows microsecond precision, despite that not being part of the ISO format.
ckan.lib.helpers.parse_rfc_2822_date(date_str, assume_utc=True)

Parse a date string of the form specified in RFC 2822, and return a datetime.

RFC 2822 is the date format used in HTTP headers. It should contain timezone information, but that cannot be relied upon.

If date_str doesn’t contain timezone information, then the ‘assume_utc’ flag determines whether we assume this string is local (with respect to the server running this code), or UTC. In practice, what this means is that if assume_utc is True, then the returned datetime is ‘aware’, with an associated tzinfo of offset zero. Otherwise, the returned datetime is ‘naive’.

If timezone information is available in date_str, then the returned datetime is ‘aware’, ie - it has an associated tz_info object.

Returns None if the string cannot be parsed as a valid datetime.

Note: in Python3, email.utils always assume UTC if there is no timezone, so assume_utc has no sense in this version.

ckan.lib.helpers.time_ago_from_timestamp(timestamp)

Returns a string like 5 months ago for a datetime relative to now :param timestamp: the timestamp or datetime :type timestamp: string or datetime

Return type:string
ckan.lib.helpers.button_attr(enable, type='primary')
ckan.lib.helpers.dataset_display_name(package_or_package_dict)
ckan.lib.helpers.resource_display_name(resource_dict)
ckan.lib.helpers.dump_json(obj, **kw)
ckan.lib.helpers.auto_log_message()
ckan.lib.helpers.activity_div(template, activity, actor, object=None, target=None)
ckan.lib.helpers.snippet(template_name, **kw)

This function is used to load html snippets into pages. keywords can be used to pass parameters into the snippet rendering

ckan.lib.helpers.convert_to_dict(object_type, objs)

This is a helper function for converting lists of objects into lists of dicts. It is for backwards compatability only.

ckan.lib.helpers.follow_button(obj_type, obj_id)

Return a follow button for the given object type and id.

If the user is not logged in return an empty string instead.

Parameters:
  • obj_type (string) – the type of the object to be followed when the follow button is clicked, e.g. ‘user’ or ‘dataset’
  • obj_id (string) – the id of the object to be followed when the follow button is clicked
Returns:

a follow button as an HTML snippet

Return type:

string

ckan.lib.helpers.follow_count(obj_type, obj_id)

Return the number of followers of an object.

Parameters:
  • obj_type (string) – the type of the object, e.g. ‘user’ or ‘dataset’
  • obj_id (string) – the id of the object
Returns:

the number of followers of the object

Return type:

int

ckan.lib.helpers.add_url_param(alternative_url=None, controller=None, action=None, extras=None, new_params=None)

Adds extra parameters to existing ones

controller action & extras (dict) are used to create the base url via url_for() controller & action default to the current ones

This can be overriden providing an alternative_url, which will be used instead.

ckan.lib.helpers.remove_url_param(key, value=None, replace=None, controller=None, action=None, extras=None, alternative_url=None)

Remove one or multiple keys from the current parameters. The first parameter can be either a string with the name of the key to remove or a list of keys to remove. A specific key/value pair can be removed by passing a second value argument otherwise all pairs matching the key will be removed. If replace is given then a new param key=replace will be added. Note that the value and replace parameters only apply to the first key provided (or the only one provided if key is a string).

controller action & extras (dict) are used to create the base url via url_for() controller & action default to the current ones

This can be overriden providing an alternative_url, which will be used instead.

ckan.lib.helpers.include_resource(resource)
ckan.lib.helpers.urls_for_resource(resource)

Returns a list of urls for the resource specified. If the resource is a group or has dependencies then there can be multiple urls.

NOTE: This is for special situations only and is not the way to generally include resources. It is advised not to use this function.

ckan.lib.helpers.debug_inspect(arg)

Output pprint.pformat view of supplied arg

ckan.lib.helpers.popular(type_, number, min=1, title=None)

display a popular icon.

ckan.lib.helpers.groups_available(am_member=False)

Return a list of the groups that the user is authorized to edit.

Parameters:am_member – if True return only the groups the logged-in user is a member of, otherwise return all groups that the user is authorized to edit (for example, sysadmin users are authorized to edit all groups) (optional, default: False)
ckan.lib.helpers.organizations_available(permission='manage_group', include_dataset_count=False)

Return a list of organizations that the current user has the specified permission for.

ckan.lib.helpers.roles_translated()

Return a dict of available roles with their translations

ckan.lib.helpers.user_in_org_or_group(group_id)

Check if user is in a group or organization

ckan.lib.helpers.dashboard_activity_stream(user_id, filter_type=None, filter_id=None, offset=0)

Return the dashboard activity stream of the current user.

Parameters:
  • user_id (string) – the id of the user
  • filter_type (string) – the type of thing to filter by
  • filter_id (string) – the id of item to filter by
Returns:

an activity stream as an HTML snippet

Return type:

string

ckan.lib.helpers.recently_changed_packages_activity_stream(limit=None)
ckan.lib.helpers.escape_js(str_to_escape)

Escapes special characters from a JS string.

Useful e.g. when you need to pass JSON to the templates

Parameters:str_to_escape – string to be escaped
Return type:string
ckan.lib.helpers.get_pkg_dict_extra(pkg_dict, key, default=None)

Returns the value for the dataset extra with the provided key.

If the key is not found, it returns a default value, which is None by default.

Parameters:pkg_dict – dictized dataset
Key:extra key to lookup
Default:default value returned if not found
ckan.lib.helpers.get_request_param(parameter_name, default=None)

This function allows templates to access query string parameters from the request. This is useful for things like sort order in searches.

Linkifies HTML

tag converted to a tag link

dataset converted to a dataset link

group converted to a group link

http:// converted to a link

ckan.lib.helpers.render_markdown(data, auto_link=True, allow_html=False)

Returns the data as rendered markdown

Parameters:
  • auto_link (bool) – Should ckan specific links be created e.g. group:xxx
  • allow_html (bool) – If True then html entities in the markdown data. This is dangerous if users have added malicious content. If False all html tags are removed.
ckan.lib.helpers.format_resource_items(items)

Take a resource item list and format nicely with blacklisting etc.

ckan.lib.helpers.resource_preview(resource, package)

Returns a rendered snippet for a embedded resource preview.

Depending on the type, different previews are loaded. This could be an img tag where the image is loaded directly or an iframe that embeds a web page or a recline preview.

ckan.lib.helpers.get_allowed_view_types(resource, package)
ckan.lib.helpers.rendered_resource_view(resource_view, resource, package, embed=False)

Returns a rendered resource view snippet.

ckan.lib.helpers.view_resource_url(resource_view, resource, package, **kw)

Returns url for resource. made to be overridden by extensions. i.e by resource proxy.

ckan.lib.helpers.resource_view_is_filterable(resource_view)

Returns True if the given resource view support filters.

ckan.lib.helpers.resource_view_get_fields(resource)

Returns sorted list of text and time fields of a datastore resource.

ckan.lib.helpers.resource_view_is_iframed(resource_view)

Returns true if the given resource view should be displayed in an iframe.

ckan.lib.helpers.resource_view_icon(resource_view)

Returns the icon for a particular view type.

ckan.lib.helpers.resource_view_display_preview(resource_view)

Returns if the view should display a preview.

ckan.lib.helpers.resource_view_full_page(resource_view)

Returns if the edit view page should be full page.

ckan.lib.helpers.remove_linebreaks(string)

Remove linebreaks from string to make it usable in JavaScript

ckan.lib.helpers.list_dict_filter(list_, search_field, output_field, value)

Takes a list of dicts and returns the value of a given key if the item has a matching value for a supplied key

Parameters:
  • list (list of dicts) – the list to search through for matching items
  • search_field (string) – the key to use to find matching items
  • output_field (string) – the key to use to output the value
  • value – the value to search for
ckan.lib.helpers.SI_number_span(number)

outputs a span with the number in SI unit eg 14700 -> 14.7k

ckan.lib.helpers.new_activities()

Return the number of activities for the current user.

See logic.action.get.dashboard_new_activities_count() for more details.

ckan.lib.helpers.uploads_enabled()

Returns a list of favourite organization in the form of organization_list action function

Returns a list of favourite group the form of organization_list action function

ckan.lib.helpers.featured_group_org(items, get_action, list_action, count)
ckan.lib.helpers.get_site_statistics()
ckan.lib.helpers.resource_formats()

Returns the resource formats as a dict, sourced from the resource format JSON file.

Parameters:
  • key – potential user input value
  • value – [canonical mimetype lowercased, canonical format (lowercase), human readable form]

Fuller description of the fields are described in ckan/config/resource_formats.json.

ckan.lib.helpers.unified_resource_format(format)
ckan.lib.helpers.check_config_permission(permission)
ckan.lib.helpers.get_organization(org=None, include_datasets=False)
ckan.lib.helpers.license_options(existing_license_id=None)

Returns [(l.title, l.id), …] for the licenses configured to be offered. Always includes the existing_license_id, if supplied.

ckan.lib.helpers.get_translated(data_dict, field)
ckan.lib.helpers.facets()

Returns a list of the current facet names

ckan.lib.helpers.mail_to(email_address, name)
ckan.lib.helpers.radio(selected, id, checked)
ckan.lib.helpers.clean_html(html)
ckan.lib.helpers.load_plugin_helpers()

(Re)loads the list of helpers provided by plugins.

ckan.lib.helpers.sanitize_id(id_)

Given an id (uuid4), if it has any invalid characters it raises ValueError.

ckan.lib.helpers.compare_pkg_dicts(old, new, old_activity_id)

Takes two package dictionaries that represent consecutive versions of the same dataset and returns a list of detailed & formatted summaries of the changes between the two versions. old and new are the two package dictionaries. The function assumes that both dictionaries will have all of the default package dictionary keys, and also checks for fields added by extensions and extra fields added by the user in the web interface.

Returns a list of dictionaries, each of which corresponds to a change to the dataset made in this revision. The dictionaries each contain a string indicating the type of change made as well as other data necessary to form a detailed summary of the change.

ckan.lib.helpers.activity_list_select(pkg_activity_list, current_activity_id)

Builds an HTML formatted list of options for the select lists on the “Changes” summary page.

ckan.lib.helpers.get_collaborators(package_id)

Return the collaborators list for a dataset

Returns a list of tuples with the user id and the capacity

ckan.lib.helpers.can_update_owner_org(package_dict, user_orgs=None)
ckan.lib.helpers.check_ckan_version(min_version=None, max_version=None)

Return True if the CKAN version is greater than or equal to min_version and less than or equal to max_version, return False otherwise.

If no min_version is given, just check whether the CKAN version is less than or equal to max_version.

If no max_version is given, just check whether the CKAN version is greater than or equal to min_version.

Parameters:
  • min_version (string) – the minimum acceptable CKAN version, eg. '2.1'
  • max_version (string) – the maximum acceptable CKAN version, eg. '2.3'
ckan.lib.helpers.csrf_input()