Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save amercader/9be404e57e5dadaf870f to your computer and use it in GitHub Desktop.
Save amercader/9be404e57e5dadaf870f to your computer and use it in GitHub Desktop.
Example of how to add a custom preview on CKAN 2.2 that embeds a URL based on a resource field
<form id="resource-edit" class="dataset-form dataset-resource-form form-horizontal" method="post" action="{{ action }}" data-module="basic-form resource-form" enctype="multipart/form-data">
...
{{ form.input('url_viz', id='field-url_viz', label=_('URL Viz'), value=data.url_viz, error=errors.url_viz, classes=[]) }}
...
{% extends 'dataviewer/base.html' %}
{% block page %}
<div>
<pre data-module="textpreview">
<div class="loading">
Add an iframe here pointing to {{ c.resource.url_viz }}
</div>
</pre>
</div>
{% endblock %}
import ckan.plugins as plugins
import ckan.plugins.toolkit as toolkit
class PluginClass(plugins.SingletonPlugin, toolkit.DefaultDatasetForm):
plugins.implements(plugins.IConfigurer)
plugins.implements(plugins.IDatasetForm)
plugins.implements(plugins.IResourcePreview)
# IConfigurer
def update_config(self, config):
# Register this extension templates directory
toolkit.add_template_directory(config, 'templates')
# IDatasetForm
# This will register our custom "url_viz" field in the resources schema
def is_fallback(self):
return True
def package_types(self):
return ('dataset',)
def _customize_package_schema(self, schema):
schema['resources']['url_viz'] = [toolkit.get_validator('not_missing')]
def create_package_schema(self):
schema = super(PluginClass, self).create_package_schema()
self._customize_package_schema(schema)
return schema
def update_package_schema(self):
schema = super(PluginClass, self).update_package_schema()
self._customize_package_schema(schema)
return schema
def show_package_schema(self):
schema = super(PluginClass, self).show_package_schema()
self._customize_package_schema(schema)
return schema
# IResourcePreview
# This configures a custom preview that looks for the "url_viz" field
# and shows an iframe to embed it
def can_preview(self, data_dict):
# Need to do this stuff because custom fields are not available
# data_dict['resource']
can_preview = False
if not data_dict.get('package'):
return can_preview
for resource in data_dict['package'].get('resources', []):
if resource['id'] == data_dict['resource']['id']:
can_preview = 'url_viz' in resource
return can_preview
def setup_template_variables(self, context, data_dict):
if not data_dict.get('package'):
return
# Need to do this stuff because custom fields are not available
# data_dict['resource']
for resource in data_dict['package'].get('resources', []):
if resource['id'] == data_dict['resource']['id']:
toolkit.c.resource['url_viz'] = resource['url_viz']
def preview_template(self, context, data_dict):
return 'embeded_viz.html'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment