2022年5月4日 星期三

CKAN Theming Tutorial 1(v2.9): 靜態檔案(圖片與CSS)

https://docs.ckan.org/en/2.9/theming/static-files.html

新增 CKAN 設定 extra_public_paths。plugin 可讓存放靜態檔案的目錄開放給 template 使用。以下以一個在首頁的 template 圖檔為例。

延續 CKAN templates Tutorial1(v2.9): 空的example_theme ,切換到 /usr/lib/ckan/default/src/ 目錄下。

public 目錄

將圖片與CSS 放在如下目錄:

ckanext-example_theme/
  ckanext/
     example_theme/
        public/
           ckan-logo.jpg
           example_theme.css


example_theme.css 檔內容:

.account-masthead {
    background-color: rgb(40, 40, 40);
}

420x220px ckan-logo.jpg

plugin.py 註冊 public 目錄

編輯 ckanext-example_theme/ckanext/example_theme/plugin.py,在 update_config() 中呼叫 add_public_directory() 向 CKAN 註冊 public 目錄:

    def update_config(self, config):
        略...

        # Add this plugin's public dir to CKAN's extra_public_paths, so
        # that CKAN will use this plugin's custom static files.
        toolkit.add_public_directory(config, 'public')

覆寫 base.html

在如下目錄新增 base.html:

ckanext-example_theme/
  ckanext/
    example_theme/
      templates/
        base.html

base.html 內容如下:

{% ckan_extends %}

{% block styles %}
  {{ super() }}
  <link rel="stylesheet" href="/example_theme.css" />
{% endblock %}

styles  block 中的內容會出現在HTML網頁的 <head>...</head> 中。

安裝

  1. 進入Python Virtual Environment: 
    . /usr/lib/ckan/default/bin/activate
  2. 切換目錄:
    cd /usr/lib/ckan/default/src/ckanext-example_theme
  3. 安裝 Plugin: 
    python setup.py develop
  4. 重啟 CKAN 服務:
    (production版) sudo supervisorctl restart ckan-uwsgi:*
    (develop版) ckan -c /etc/ckan/default/ckan.ini run

測試

http://[CKAN Website IP]/ckan-logo.jpghttp://[CKAN Website IP]/example_theme.css 可看到對應內容。

檢視 http://[CKAN Website IP] 的網頁原始碼,在HTML的 <head>...</head> 可發現:

<link rel="stylesheet" href="/example_theme.css" />




沒有留言:

張貼留言