http://docs.ckan.org/en/2.9/theming/templates.html#template-helper-functions
若要讀出 CKAN 裡的資訊,template helper function 是方法之一。
內建的 template helper functions
延續 上個 CKAN templates Tutorial,將 example_theme 底下的 templates/home/layout1.html 修改如下:
{% ckan_extends %}
{% block featured_group %}
<p>recently_changed_packages_activity_stream</p>
<ul>
{% for stream in h.recently_changed_packages_activity_stream(limit=4) %}
<li>stream id: {{ stream.id }}</li>
{% endfor %}
</ul>
{% endblock %}
以 h 開頭的 h.recently_changed_packages_activity_stream,便是 template helper function,可讀出最近資料集(package)的更新資訊 ,結果如下:
在 templates 裡可透過 h 全域變數呼叫 ckan.lib.helpers 底下的 template helper function。參考:Template helper functions reference。
自訂 template helper functions
實作 ckan.plugins.interfaces.ITemplateHelpers,列出最受歡迎的 group。
修改 plugin.py
import ckan.plugins as plugins
import ckan.plugins.toolkit as toolkit
def most_popular_groups():
'''Return a sorted list of the groups with the most datasets.'''
# Get a list of all the site's groups from CKAN, sorted by number of
# datasets.
groups = toolkit.get_action('group_list')(
data_dict={'sort': 'package_count desc', 'all_fields': True})
# Truncate the list to the 10 most popular groups only.
groups = groups[:10]
return groups
class ExampleThemePlugin(plugins.SingletonPlugin):
'''An example theme plugin.
'''
plugins.implements(plugins.IConfigurer)
# Declare that this plugin will implement ITemplateHelpers.
plugins.implements(plugins.ITemplateHelpers)
def update_config(self, config):
# Add this plugin's templates dir to CKAN's extra_template_paths, so
# that CKAN will use this plugin's custom templates.
toolkit.add_template_directory(config, 'templates')
def get_helpers(self):
'''Register the most_popular_groups() function above as a template
helper function.
'''
# Template helper function names should begin with the name of the
# extension they belong to, to avoid clashing with functions from
# other extensions.
return {'example_theme_most_popular_groups': most_popular_groups}
修改 layout1.html
修改 ckanext-example_theme/ckanext/example_theme/templates/home/layout1.html 如下:
{% ckan_extends %}
{% block featured_group %}
{{ h.recently_changed_packages_activity_stream(limit=4) }}
{% endblock %}
{% block featured_organization %}
{# Show a list of the site's most popular groups. #}
<h3>Most popular groups</h3>
<ul>
{% for group in h.example_theme_most_popular_groups() %}
<li>{{ group.display_name }}</li>
{% endfor %}
</ul>
{% endblock %}
測試
重新安裝 plugin
切換到 ckanext-example_theme 目錄,執行:
cd ckanext-example_theme
python setup.py develop
重啟 CKAN
- 進入Python Virtual Environment:
. /usr/lib/ckan/default/bin/activate - 重啟 CKAN 服務:
(production版) sudo supervisorctl restart ckan-uwsgi:*
(develop版) ckan -c /etc/ckan/default/ckan.ini run
結果如下:
沒有留言:
張貼留言