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)
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(controller='package', action='read',
                    id='my_dataset')

Or, using a named route:

toolkit.redirect_to('dataset_read', id='changed')
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 the given controller, action, id, etc.

Usage:

import ckan.plugins.toolkit as toolkit

url = toolkit.url_for(controller='package', action='read',
                      id='my_dataset')
=> returns '/dataset/my_dataset'

Or, using a named route:

toolkit.url_for('dataset_read', id='changed')

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

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

This is a wrapper for routes.url_for()

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.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 langage name currently used in it’s localised form either from parameter or current environ setting

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

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
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.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, 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. limit – the max. number of facet items to return. exclude_active – only return unselected facets.

ckan.lib.helpers.has_more_facets(facet, 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. 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_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.linked_user(user, maxlength=0, avatar=20)
ckan.lib.helpers.group_name_to_title(name)
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.linked_gravatar(email_hash, size=100, default=None)
ckan.lib.helpers.gravatar(email_hash, size=100, default=None)
ckan.lib.helpers.pager_url(page, partial=None, **kwargs)
class ckan.lib.helpers.Page(collection, page=1, items_per_page=20, item_count=None, sqlalchemy_session=None, presliced_list=False, url=None, **kwargs)
pager(*args, **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)

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
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.

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='edit_group')

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.load_plugin_helpers()

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