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')
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.
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.
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 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
- class – pass extra class(es) to add to the
build a set of menu items.
args: tuples of (menu type, title) eg (‘login’, _(‘Login’)) outputs <li><a href=”…”>title</a></li>
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
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
Build extra navigation items used in
admin/base.html
for values defined in the config optionckan.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)¶ Return string with links to other pages (e.g. “1 2 [3] 4 5 6 7”).
- format:
Format string that defines how the pager is rendered. The string can contain the following $-tokens that are substituted by the string.Template module:
- $first_page: number of first reachable page
- $last_page: number of last reachable page
- $page: number of currently selected page
- $page_count: number of reachable pages
- $items_per_page: maximal number of items per page
- $first_item: index of first item on the current page
- $last_item: index of last item on the current page
- $item_count: total number of items
- $link_first: link to first page (unless this is first page)
- $link_last: link to last page (unless this is last page)
- $link_previous: link to previous page (unless this is first page)
- $link_next: link to next page (unless this is last page)
To render a range of pages the token ‘~3~’ can be used. The number sets the radius of pages around the current page. Example for a range with radius 3:
‘1 .. 5 6 7 [8] 9 10 11 .. 500’
Default: ‘~2~’
- symbol_first
String to be displayed as the text for the %(link_first)s link above.
Default: ‘<<’
- symbol_last
String to be displayed as the text for the %(link_last)s link above.
Default: ‘>>’
- symbol_previous
String to be displayed as the text for the %(link_previous)s link above.
Default: ‘<’
- symbol_next
String to be displayed as the text for the %(link_next)s link above.
Default: ‘>’
- separator:
String that is used to separate page links/numbers in the above range of pages.
Default: ‘ ‘
- page_param:
The name of the parameter that will carry the number of the page the user just clicked on. The parameter will be passed to a url_for() call so if you stay with the default ‘:controller/:action/:id’ routing and set page_param=’id’ then the :id part of the URL will be changed. If you set page_param=’page’ then url_for() will make it an extra parameters like ‘:controller/:action/:id?page=1’. You need the page_param in your action to determine the page number the user wants to see. If you do not specify anything else the default will be a parameter called ‘page’.
Note: If you set this argument and are using a URL generator callback, the callback must accept this name as an argument instead of ‘page’. callback, becaust the callback requires its argument to be ‘page’. Instead the callback itself can return any URL necessary.
- partial_param:
When using AJAX/AJAH to do partial updates of the page area the application has to know whether a partial update (only the area to be replaced) or a full update (reloading the whole page) is required. So this parameter is the name of the URL parameter that gets set to 1 if the ‘onclick’ parameter is used. So if the user requests a new page through a Javascript action (onclick) then this parameter gets set and the application is supposed to return a partial content. And without Javascript this parameter is not set. The application thus has to check for the existence of this parameter to determine whether only a partial or a full page needs to be returned. See also the examples in this modules docstring.
Default: ‘partial’
Note: If you set this argument and are using a URL generator callback, the callback must accept this name as an argument instead of ‘partial’.
- show_if_single_page:
if True the navigator will be shown even if there is only one page
Default: False
- link_attr (optional)
A dictionary of attributes that get added to A-HREF links pointing to other pages. Can be used to define a CSS style or class to customize the look of links.
Example: { ‘style’:’border: 1px solid green’ }
Default: { ‘class’:’pager_link’ }
- curpage_attr (optional)
A dictionary of attributes that get added to the current page number in the pager (which is obviously not a link). If this dictionary is not empty then the elements will be wrapped in a SPAN tag with the given attributes.
Example: { ‘style’:’border: 3px solid blue’ }
Default: { ‘class’:’pager_curpage’ }
- dotdot_attr (optional)
A dictionary of attributes that get added to the ‘..’ string in the pager (which is obviously not a link). If this dictionary is not empty then the elements will be wrapped in a SPAN tag with the given attributes.
Example: { ‘style’:’color: #808080’ }
Default: { ‘class’:’pager_dotdot’ }
- onclick (optional)
This paramter is a string containing optional Javascript code that will be used as the ‘onclick’ action of each pager link. It can be used to enhance your pager with AJAX actions loading another page into a DOM object.
In this string the variable ‘$partial_url’ will be replaced by the URL linking to the desired page with an added ‘partial=1’ parameter (or whatever you set ‘partial_param’ to). In addition the ‘$page’ variable gets replaced by the respective page number.
Note that the URL to the destination page contains a ‘partial_param’ parameter so that you can distinguish between AJAX requests (just refreshing the paginated area of your page) and full requests (loading the whole new page).
[Backward compatibility: you can use ‘%s’ instead of ‘$partial_url’]
- jQuery example:
- “$(‘#my-page-area’).load(‘$partial_url’); return false;”
- Yahoo UI example:
- “YAHOO.util.Connect.asyncRequest(‘GET’,’$partial_url’,{
- success:function(o){YAHOO.util.Dom.get(‘#my-page-area’).innerHTML=o.responseText;} },null); return false;”
- scriptaculous example:
- “new Ajax.Updater(‘#my-page-area’, ‘$partial_url’,
- {asynchronous:true, evalScripts:true}); return false;”
- ExtJS example:
- “Ext.get(‘#my-page-area’).load({url:’$partial_url’}); return false;”
- Custom example:
- “my_load_page($page)”
Additional keyword arguments are used as arguments in the links. Otherwise the link will be created with url_for() which points to the page you are currently displaying.
-
-
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.
dataset_display_name
(package_or_package_dict)¶
-
ckan.lib.helpers.
dataset_link
(package_or_package_dict)¶
-
ckan.lib.helpers.
resource_display_name
(resource_dict)¶
-
ckan.lib.helpers.
resource_link
(resource_dict, package_id)¶
-
ckan.lib.helpers.
tag_link
(tag)¶
-
ckan.lib.helpers.
group_link
(group)¶
-
ckan.lib.helpers.
organization_link
(organization)¶
-
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.
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 onesThis 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 onesThis 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.
-
ckan.lib.helpers.
html_auto_link
(data)¶ 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
()¶
-
ckan.lib.helpers.
get_featured_organizations
(count=1)¶ Returns a list of favourite organization in the form of organization_list action function
-
ckan.lib.helpers.
get_featured_groups
(count=1)¶ 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.
mail_to
(email_address, name)¶
-
ckan.lib.helpers.
radio
(selected, id, checked)¶
-
ckan.lib.helpers.
sanitize_id
(id_)¶ Given an id (uuid4), if it has any invalid characters it raises ValueError.
-
ckan.lib.helpers.
load_plugin_helpers
()¶ (Re)loads the list of helpers provided by plugins.