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

Collection of CKAN native and extension-provided helpers.

class ckan.lib.helpers.literal(base: Any = '', encoding: Optional[str] = None, errors: str = 'strict')

Represents an HTML literal.

classmethod escape(s: Optional[str]) Markup

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

ckan.lib.helpers.core_helper(f: Helper, name: Optional[str] = None) Helper

Register a function as a builtin helper method.

ckan.lib.helpers.chained_helper(func: Helper) Helper

Decorator function allowing helper functions to be chained.

This chain starts with the first chained helper to be registered and ends with the original helper (or a non-chained plugin override version). Chained helpers must accept an extra parameter, specifically the next helper in the chain, for example:

helper(next_helper, *args, **kwargs).

The chained helper function may call the next_helper function, optionally passing different values, handling exceptions, returning different values and/or raising different exceptions to the caller.

Usage:

from ckan.plugins.toolkit import chained_helper

@chained_helper
def ckan_version(next_func, **kw):

    return next_func(**kw)
Parameters

func (callable) – chained helper function

Returns

chained helper function

Return type

callable

ckan.lib.helpers.redirect_to(*args: Any, **kw: Any) Response

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

This is a wrapper for flask.redirect() 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.
return toolkit.redirect_to('dataset.read',
                    id='my_dataset')

Or, using a named route:

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

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

return toolkit.redirect_to(’http://example.com’) return toolkit.redirect_to(‘/dataset’) return toolkit.redirect_to(‘/some/other/path’)

ckan.lib.helpers.get_site_protocol_and_host() Union[tuple[str, str], tuple[None, None]]

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: Any, **kw: Any) str

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: Any, **kw: Any) str

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: Any, **kw: Any) str

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

ckan.lib.helpers.is_url(*args: Any, **kw: Any) bool

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

ckan.lib.helpers.url_is_local(url: str) bool

Returns True if url is local

ckan.lib.helpers.full_current_url() str

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

ckan.lib.helpers.current_url() str

Returns current url unquoted

ckan.lib.helpers.lang() Optional[str]

Return the language code for the current locale eg en

ckan.lib.helpers.strxfrm(s: str) str

Transform a string to one that can be used in locale-aware comparisons. Override this helper if you have different text sorting needs.

ckan.lib.helpers.ckan_version() str

Return CKAN version

ckan.lib.helpers.lang_native_name(lang_: Optional[str] = None) Optional[str]

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

ckan.lib.helpers.is_rtl_language() bool
ckan.lib.helpers.get_rtl_theme() str
ckan.lib.helpers.flash_notice(message: Any, allow_html: bool = False) None

Show a flash message of type notice

ckan.lib.helpers.flash_error(message: Any, allow_html: bool = False) None

Show a flash message of type error

ckan.lib.helpers.flash_success(message: Any, allow_html: bool = False) None

Show a flash message of type success

ckan.lib.helpers.get_flashed_messages(**kwargs: Any)

Call Flask’s built in get_flashed_messages

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: Union[tuple[str, str], tuple[str, str, list[str]], tuple[str, str, list[str], str]]) Markup

Build a set of menu items.

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

Parameters

args (tuple[str, str, Optional[list], Optional[str]]) – tuples of (menu type, title) eg (‘login’, _(‘Login’)). Third item specifies controllers which should be used to mark link as active. Fourth item specifies auth function to check permissions against.

Return type

str

ckan.lib.helpers.build_nav_icon(menu_item: str, title: str, **kw: Any) Markup

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: str, title: str, **kw: Any) Markup

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: str)

returns flask routes for old fashioned route names

ckan.lib.helpers.build_extra_admin_nav() Markup

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(type_: str) str

Get default group/organization type for using site-wide.

ckan.lib.helpers.default_package_type() str

Get default package type for using site-wide.

ckan.lib.helpers.humanize_entity_type(entity_type: str, object_type: str, purpose: str) Optional[str]

Convert machine-readable representation of package/group type into human-readable form.

Returns capitalized entity_type with all underscores converted into spaces.

Example:

>>> humanize_entity_type('group', 'custom_group', 'add link')
'Add Custom Group'
>>> humanize_entity_type('group', 'custom_group', 'breadcrumb')
'Custom Groups'
>>> humanize_entity_type('group', 'custom_group', 'not real purpuse')
'Custom Group'
Possible purposes(depends on entity_type and change over time):

add link: “Add [object]” button on search pages breadcrumb: “Home / [object]s / New” section in breadcrums content tab: “[object]s | Groups | Activity” tab on details page create label: “Home / … / Create [object]” part of breadcrumb create title: “Create [object] - CKAN” section of page title delete confirmation: Confirmation popup when object is deleted description placeholder: Placeholder for description field on form edit label: “Edit [object]” label/breadcrumb/title facet label: “[object]s” label in sidebar(facets/follower counters) form label: “[object] Form” heading on object form page main nav: “[object]s” link in the header view label: “View [object]s” button on edit form my label: “My [object]s” tab in dashboard name placeholder: “<[object]>” section of URL preview on object form no any objects: No objects created yet no associated label: no gorups for dataset no description: object has no description no label: package with no organization page title: “Title - [objec]s - CKAN” section of page title save label: “Save [object]” button search placeholder: “Search [object]s…” placeholder update label: “Update [object]” button you not member: Dashboard with no groups

ckan.lib.helpers.get_facet_items_dict(facet: str, search_facets: Union[dict[str, dict[str, Any]], Any] = None, limit: Optional[int] = None, exclude_active: bool = False) list[dict[str, Any]]

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

ckan.lib.helpers.has_more_facets(facet: str, search_facets: dict[str, dict[str, Any]], limit: Optional[int] = None, exclude_active: bool = False) bool

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

ckan.lib.helpers.get_param_int(name: str, default: int = 10) int
ckan.lib.helpers.sorted_extras(package_extras: list[dict[str, Any]], auto_clean: bool = False, subs: Optional[dict[str, str]] = None, exclude: Optional[list[str]] = None) list[tuple[str, Any]]

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: str, data_dict: Optional[dict[str, Any]] = None) bool
ckan.lib.helpers.linked_user(user: Union[str, User], maxlength: int = 0, avatar: int = 20) Optional[Union[Markup, str]]
ckan.lib.helpers.group_name_to_title(name: str) str
ckan.lib.helpers.markdown_extract(text: str, extract_length: int = 190) Union[str, Markup]

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.dict_list_reduce(list_: list[dict[str, T]], key: str, unique: bool = True) list[T]

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: str, size: int = 100, default: Optional[str] = None) Markup
ckan.lib.helpers.sanitize_url(url: str)

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: str, size: int = 100) Union[Markup, str]
ckan.lib.helpers.pager_url(page: int, partial: Optional[str] = None, **kwargs: Any) str
ckan.lib.helpers.get_page_number(params: dict[str, Any], key: str = 'page', default: int = 1) int

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() tzinfo

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_: Optional[datetime], date_format: Optional[str] = None, with_hours: bool = False, with_seconds: bool = False) str

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: str) datetime

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: str, assume_utc: bool = True) Optional[datetime]

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: int) str

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.dataset_display_name(package_or_package_dict: Union[dict[str, Any], model.Package]) str
ckan.lib.helpers.resource_display_name(resource_dict: dict[str, Any]) str
ckan.lib.helpers.dump_json(obj: Any, **kw: Any) str
ckan.lib.helpers.snippet(template_name: str, **kw: Any) str

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: str, objs: list[Any]) list[dict[str, Any]]

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: str, obj_id: str) str

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: str, obj_id: str) int

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: Optional[str] = None, controller: Optional[str] = None, action: Optional[str] = None, extras: Optional[dict[str, Any]] = None, new_params: Optional[dict[str, Any]] = None) str

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: Union[list[str], str], value: Optional[str] = None, replace: Optional[str] = None, controller: Optional[str] = None, action: Optional[str] = None, extras: Optional[dict[str, Any]] = None, alternative_url: Optional[str] = None) str

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.debug_inspect(arg: Any) Markup

Output pprint.pformat view of supplied arg

ckan.lib.helpers.popular(type_: str, number: int, min: int = 1, title: Optional[str] = None) str

display a popular icon.

ckan.lib.helpers.groups_available(am_member: bool = False) list[dict[str, Any]]

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: str = 'manage_group', include_dataset_count: bool = False) list[dict[str, Any]]

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

ckan.lib.helpers.roles_translated() dict[str, str]

Return a dict of available roles with their translations

ckan.lib.helpers.user_in_org_or_group(group_id: str) bool

Check if user is in a group or organization

ckan.lib.helpers.escape_js(str_to_escape: str) str

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: dict[str, Any], key: str, default: Optional[Any] = None) Any

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: str, default: Optional[Any] = None) Any

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: str, auto_link: bool = True, allow_html: bool = False) Union[str, Markup]

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: list[tuple[str, Any]]) list[tuple[str, Any]]

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

ckan.lib.helpers.get_allowed_view_types(resource: dict[str, Any], package: dict[str, Any]) list[tuple[str, str, str]]
ckan.lib.helpers.rendered_resource_view(resource_view: dict[str, Any], resource: dict[str, Any], package: dict[str, Any], embed: bool = False) Markup

Returns a rendered resource view snippet.

ckan.lib.helpers.view_resource_url(resource_view: dict[str, Any], resource: dict[str, Any], package: dict[str, Any], **kw: Any) str

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

ckan.lib.helpers.resource_view_is_filterable(resource_view: dict[str, Any]) bool

Returns True if the given resource view support filters.

ckan.lib.helpers.resource_view_get_fields(resource: dict[str, Any]) list['str']

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

ckan.lib.helpers.resource_view_is_iframed(resource_view: dict[str, Any]) bool

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

ckan.lib.helpers.resource_view_icon(resource_view: dict[str, Any]) str

Returns the icon for a particular view type.

ckan.lib.helpers.resource_view_display_preview(resource_view: dict[str, Any]) bool

Returns if the view should display a preview.

ckan.lib.helpers.resource_view_full_page(resource_view: dict[str, Any]) bool

Returns if the edit view page should be full page.

ckan.lib.helpers.remove_linebreaks(string: str) str

Remove linebreaks from string to make it usable in JavaScript

ckan.lib.helpers.list_dict_filter(list_: list[dict[str, Any]], search_field: str, output_field: str, value: Any) Any

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: int) Markup

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

ckan.lib.helpers.uploads_enabled() bool

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: list[str], get_action: str, list_action: str, count: int) list[dict[str, Any]]
ckan.lib.helpers.get_site_statistics() dict[str, int]
ckan.lib.helpers.resource_formats_default_file()
ckan.lib.helpers.resource_formats() dict[str, list[str]]

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: str) str
ckan.lib.helpers.check_config_permission(permission: str) Union[list[str], bool]
ckan.lib.helpers.get_organization(org: Optional[str] = None, include_datasets: bool = False) dict[str, Any]
ckan.lib.helpers.license_options(existing_license_id: Optional[tuple[str, str]] = None) list[tuple[str, str]]

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: dict[str, Any], field: str) Union[str, Any]
ckan.lib.helpers.facets() list[str]

Returns a list of the current facet names

ckan.lib.helpers.mail_to(email_address: str, name: str) Markup
ckan.lib.helpers.clean_html(html: Any) str
ckan.lib.helpers.load_plugin_helpers() None

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

ckan.lib.helpers.sanitize_id(id_: str) str

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

ckan.lib.helpers.get_collaborators(package_id: str) list[tuple[str, str]]

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: dict[str, Any], user_orgs: Optional[list[dict[str, Any]]] = None) bool
ckan.lib.helpers.decode_view_request_filters() dict[str, Any] | None
ckan.lib.helpers.check_ckan_version(min_version: Optional[str] = None, max_version: Optional[str] = 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.make_login_url(login_view: str, next_url: Optional[str] = None, next_field: str = 'next') str

Creates a URL for redirecting to a login page. If only login_view is provided, this will just return the URL for it. If next_url is provided, however, this will append a next=URL parameter to the query string so that the login view can redirect back to that URL.

ckan.lib.helpers.csrf_input()