2022年5月5日 星期四

CKAN v2.9 templates 3: Jinja2

Jinjia2

CKAN template 以 Jinja2 撰寫。

敍述式及變數

{{ ... }} 中即 Jinja2 敍述式,最後放入執行結果。

{{ foo }} 會顯示成變數 foo 的值。

template 可用 CKAN 的許多全域變數,像是 app_globals 用 g 別名取得 CKAN 設定檔中部分設定,例如 ckan.site_title:

<p>The title of this site is: {{ g.site_title }}.</p>

其他可參考:http://docs.ckan.org/en/2.9/theming/variables-and-functions.html。

並不是所有設定都讀得到,自訂設定就讀不到,參考:CKAN Templates Tutorial 9(v2.9): 存取自訂的 config 設定。

若 template 要讀取的變數不存在,不會 crash 也不會有錯誤訊息,Jinja2 只會傳回空字串。

{{ g.an_attribute_that_does_not_exist }}
{{ a_variable_that_does_not_exist }}

但如果要產生不存在變數的 attribute,Jinja2 會 crash,如下:

{{ a_variable_that_does_not_exist.an_attribute_that_does_not_exist }}

UndefinedError: 'a_variable_that_does_not_exist' is undefined

Jinja2 不只是列印變數,還可以呼叫 Jinja2 的 global functions, CKAN 的 template helper functions 及自訂的 template helper functions。參考:Variables and functions available to templates。

Jinja tags

{% ... %} 裡的 Jinja tags 可控制程式邏輯。我們可以顯示啟用的 plugin 清單:

<ul>
  {% for plugin in g.plugins %}
    <li>{{ plugin }}</li>
  {% endfor %}
</ul>

用 Jinja’s {% if %} 測試條件:

{% if g.tracking_enabled %}
  <p>CKAN's page-view tracking feature is enabled.</p>
{% else %}
  <p>CKAN's page-view tracking feature is <i>not</i> enabled.</p>
{% endif %}

註解

{# ... #} 裡的是註解。

{# This text will not appear in the output when this template is rendered. #}

修改 index.html

修改上個 tutorial 產生的 home/index.html 如下:

{# Jinja variable example #}
<p>The title of this site is: {{ g.site_title }}.</p>
{# End example #}

{# Jinja for-loop example #}
<p>The currently enabled plugins are:</p>
<ul>
  {% for plugin in g.plugins %}
    <li>{{ plugin }}</li>
  {% endfor %}
</ul>
{# End example #}

{# Jinja if example #}
{% if g.tracking_enabled %}
  <p>CKAN's page-view tracking feature is enabled.</p>
{% else %}
  <p>CKAN's page-view tracking feature is <i>not</i> enabled.</p>
{% endif %}
{# End example #}

重啟 CKAN

  1. 進入Python Virtual Environment: 
    . /usr/lib/ckan/default/bin/activate
  2. 重啟 CKAN 服務:
    (production版) sudo supervisorctl restart ckan-uwsgi:*
    (develop版) ckan -c /etc/ckan/default/ckan.ini run

測試

重新瀏覽 http://[CKAN web site]/



CKAN v2.9 templates 2: 取代預設的 template

http://docs.ckan.org/en/2.9/theming/templates.html#replacing-a-default-template-file

每個 CKAN 網頁都由對應的 template 產生,如:

  • /index --> ckan/templates/home/index.html
  • /about --> ckan/templates/home/about.html
  • /dataset --> ckan/templates/package/search.html

要自訂,plugin 需註冊一個包含 template 的 template 目錄來覆寫 CKAN 的預設內容。

延續上個 CKAN templates Tutorial 1(v2.9): 空的example_theme。

修改 plugin.py

修改 ckanext-example_theme/ckanext/example_theme/plugin.py,如下:

import ckan.plugins as plugins
import ckan.plugins.toolkit as toolkit

class ExampleThemePlugin(plugins.SingletonPlugin):
    plugins.implements(plugins.IConfigurer)

    def update_config(self, config):
        toolkit.add_template_directory(config, 'templates')

程式中:

  • import ckan.plugins.toolkit as toolkit
    plugins toolkit 是 Python module 提供 CKAN plugins 必要的 functions, classes 及 exceptions。
  • plugins.implements(plugins.IConfigurer)
    實作 plugins.IConfigurer
  • def update_config
    實作 plugins.IConfigurer 介面的 update_config。
    CKAN 會在啟動時呼叫 IConfigurer 介面的 update_config,讓我們有機會修改 CKAN 的設定。
  • ckan.plugins.toolkit.add_template_directory 向 CKAN 註冊 template 目錄,告訴 CKAN 產生/render 網頁時來找這個plugin目錄下的 templates 目錄。
    只要與 CKAN 預設 template 同名的檔案就會取代掉原本的。

查看 CKAN 使用的 template

修改 /etc/ckan/default/ckan.ini 中的 debug = true。

重新載入 CKAN 首頁,會看到下方有個 Debug 連結,按下後展開 debug footer 顯示許多偵錯資訊,其中便有產生此網頁的 template 檔名。

Template name: home/index.html
Template path: /usr/lib/ckan/default/src/ckan/ckan/templates/home/index.html

大部分的 CKAN 網頁由多個 template 產生,第一個是 root template,其它則是相關的 included 檔。

覆寫 home/index.html

在 ckanext-example_theme 目錄下為要覆寫的 template 建立對應的目錄及檔案,如:
  ckanext/
    example_theme/
      templates/
        home/
          index.html  

編輯 index.html 如下:

Hello new Index Page! 中文也沒問題!

如果執行 ckan 沒有用 -r(--disable-reloader) 選項,如此修改 Python file,  template file,  CKAN config file, 或其它 CKAN file 都不需重啟伺服器。但如果是新加檔案、目錄就要重啟。

測試

重新瀏覽 http://[你的IP]/



CKAN v2.9 templates 1: 空的example_theme

http://docs.ckan.org/en/2.9/theming/templates.html

CKAN 網頁由 Jinja2 template 產生。以下練習將修改 layout 及預設內容。

CKAN theme 就是 CKAN plugin,內含自訂的 templates、靜態檔案。

建立: ckanext-example_theme

  • 啟用 CKAN Virtual Environment
. /usr/lib/ckan/default/bin/activate
  • 切換到 /usr/lib/ckan/default/src 執行 ckan generate extension
Extension's name [must begin 'ckanext-']: ckanext-example_theme
 
ckanext-example_theme
├── ckanext
│   ├── example_theme
│   │   ├── assets
│   │   │   └── webassets.yml
│   │   ├── fanstatic
│   │   ├── i18n
│   │   ├── __init__.py
│   │   ├── plugin.py
│   │   ├── public
│   │   ├── templates
│   │   └── tests
│   │       ├── __init__.py
│   │       └── test_plugin.py
│   └── __init__.py
├── dev-requirements.txt
├── LICENSE
├── MANIFEST.in
├── README.md
├── requirements.txt
├── setup.cfg
├── setup.py
└── test.ini
 

修改 plugin.py 

所有 CKAN plugin 都需繼承自 plugins.SingletonPlugin。修改 ckanext-example_theme/ckanext/example_theme/plugin.py 如下:

import ckan.plugins as plugins

class ExampleThemePlugin(plugins.SingletonPlugin):
    '''An example theme plugin.

    '''
    pass


        修改並執行 setup.py 

        修改 ckanext-example_theme/setup.py 的 entry_points
        entry_points='''
            [ckan.plugins]
            example_theme=ckanext.example_theme.plugin:ExampleThemePlugin
        ''',

        切換到 ckanext-example_theme 目錄,執行:

        cd ckanext-example_theme
        python setup.py develop


        修改 /etc/ckan/default/ckan.ini 並重啟 CKAN

        extension plugins 必須加到 CKAN 設定檔的 ckan.plugins 中,CKAN 才會呼叫。

        ckan.plugins = stats text_view 略... example_theme

        重啟 CKAN

        1. 進入Python Virtual Environment: 
          . /usr/lib/ckan/default/bin/activate
        2. 重啟 CKAN 服務:
          (production版) sudo supervisorctl restart ckan-uwsgi:*
          (develop版) ckan -c /etc/ckan/default/ckan.ini run

        測試

        重新載入 http://[CKAN web site]/

        沒錯就是對了。

        2022年5月4日 星期三

        CKAN 前端開發(v2.9): 自訂 base template

         http://docs.ckan.org/en/2.9/contributing/frontend/template-tutorial.html

        page.html 提供基本 CKAN 網頁結構及其 header、footer。

        {% extends "page.html" %}

        page.html template 中有許多 block 可擴充,最常用的就是 *_content:

        • primary_content
        • secondary_content: sidebar
        • breadcrumb_content
        • actions_content: breadcrumb 左邊的 actions bar 

        Primary Content

        加入以下內容:

        {% block primary_content %}
          {{ super() }}

          {% block my_content %}
            <h2>{{ _('This is my content heading') }}</h2>
            <p>{{ _('This is my content') }}</p>
          {% endblock %}
        {% endblock %}

        把內容放在 block,如此其他 template 也能覆寫。

        Secondary Content

        通常由 reusable module 的 snippet 內容組成。snippet 可讓 template 保持簡潔,方便 theme extension 覆寫。

        {% block primary_content %}
          {{ super() }}
          {% block my_sidebar_module %}
            {% snippet "snippets/my-sidebar-module.html" %}
          {% endblock %}
        {% endblock %}

        Breadcrumb 及 Actions

        每個網頁上方都有 breadcrumb ,也用來顯示這個網頁可做的 action。

        {% block breadcrumb_content %}
          <li class="active">{% link_for _('Viewing Dataset'), named_route=pkg.type ~ '.read', id=pkg.id %}</li>
        {% endblock %}

        {% block actions_content %}
          {{ super() }}
          <li class="active">{% link_for _('New Dataset'), named_route='dataset.new', class_='btn', icon='plus' %}</li>
        {% endblock %}

        Scripts 及 Stylesheets

        透過 styles 及 scripts 這兩個 block 可自訂樣式及 JavaScript。這功能將被 {% resource %} 取代。

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

        {% block scripts %}
          {{ super() }}
          <script src="{% url_for_static "my-script.js" %}"></script>
        {% endblock %}

        CKAN 前端開發(v2.9): form macros

        http://docs.ckan.org/en/2.9/contributing/frontend/templating.html#form-macros

        CKAN 用 form macro 產生基本的表單輸入欄位,複雜的自己寫。

        這些 macros 可用 {% import %} 匯入網頁。如下:

        {% import 'macros/form.html' as form %}

        form.input()

        包含產生對應的 label, error message。

        name        - The name of the form parameter.
        id          - The id to use on the input and label. Convention is to prefix with 'field-'.
        label       - The human readable label.
        value       - The value of the input.
        placeholder - Some placeholder text.
        type        - The type of input eg. email, url, date (default: text).
        error       - A list of error strings for the field or just true to highlight the field.
        classes     - An array of classes to apply to the control-group.
        attrs       - Dictionary of extra tag attributes
        is_required - Boolean of whether this input is required for the form to validate

        如:

        {% import 'macros/form.html' as form %}
        {{ form.input('title', label=_('Title'), value=data.title, error=errors.title) }}

        其餘參考: http://docs.ckan.org/en/2.9/contributing/frontend/templating.html#form-macros



        CKAN 前端開發(v2.9): template

        http://docs.ckan.org/en/2.9/contributing/frontend/templating.html

        template 搜尋順序

        以 user/index.html 為例,CKAN 會依以下順序去找:

        1. 所有載入 extension 的 template 目錄
        2. 所有載入 extension 的 template_legacy 目錄
        3. CKAN 的 template 目錄
        4. CKAN 的 template_legacy 目錄
        以上的 legacy 指的是 Genshi template,它們全都被放在 templates_legacy 目錄。若 template 目錄找不到,才會去 legacy 目錄下找。在 CKAN 升級至新版向前相容。

        檔案結構

        師之前版本一樣,每個 controller 一個目錄、每個 action 一個 template 檔案。

        controller 下的 snippets 目錄存放此 controller 專用的 snippet,通用的 snippet 則放在上層目錄。

        templates/
          base.html             # A base template with just core HTML structure
          page.html             # A base template with default page layout
          header.html           # The site header.
          footer.html           # The site footer.
          snippets/             # A folder of generic sitewide snippets
          home/
            index.html          # Template for the index action of the home controller
            snippets/           # Snippets for the home controller
          user/
            ...
        templates_legacy/
          # All ckan templates

        templating system

        Jinja2 使用很多 template 繼承的功能來產生網頁。action 的 template 大多也繼承自 page.html:

        {% extends "page.html" %}

        其中有許多 block 可讓子 template 覆寫。page.html 決定了基本頁面內容架構,通常只有 {% block primary_content %} 需要自訂。

        {% extends "page.html" %}
        {% block page_content.html %}
          <h1>My page title</h1>
          <p>This content will be added to the page</p>
        {% endblock %}

        慣例/Conventions

        Includes

        儘量少用 Include。 {% include %} 的內容需放在使用它的程式下的 _snippets_ 目錄。

        通常會用 {% snippet %} ,除非 parents context 只能被此 snippet 使用。

        Snippets

        用 {% snippet %} 比 h.snippet() 好。

        snippet 介於 include 和 macro 之間,透過參數決定那些資訊要傳入 snippet。(include 只能接收到 父 context).

        儘量 include,因為可讓偵錯變簡單。

        Macros

        Macros 應節制使用在為通用的 code snippet 建立 custom generator。像是 macros/form.html  中用 macro 來建立表單欄位。

        儘量少用,marcro不好擴充及自訂。

        extension 中的 template

        在 plugin 呼叫 update_config() 向 CKAN 註冊額外的 template 路徑/extra_template_paths。

        Custom Control Structures

        {% ckan_extends %}

        用法和 {% extend %} 很像,但它會向上載入下一個 template。

        如果要移除使用者資訊頁面的 breadcrumb。

        1. 先確定要覆寫的 template:
          ckan/templates/user/read.html
        2. 在你的 extension 的 template 目錄下,建立對應要覆寫的目錄及檔案:
          ckanext-mytheme/ckanext/mytheme/templates/user/read.html
        3. 在 read.html 中透過 {% ckan_extends %} 拉出 CKAN 核心網頁內容:
          {% ckan_extends %}
        4. 然後覆寫原本的 breadcrumb block:
          {% ckan_extends %}
          {# 以下會移除 breadcrumb #}
          {% block breadcrumb %}{% endblock %}

        {% ckan_extends %} 會 recursively 執行,{% ckan_extend %} 只會套用在相同名稱的 template。

        {% snippet [filepath], [arg1=arg1], [arg2=arg2]... %}

        很像 Jinja2 的 {% include %},差別在 CKAN 的 snippet 不會繼承 parent template 的 context,也就是只有明確傳入的參數可用,好處是容易偵錯。用法如下:

        {% snippet "package/snippets/package_form.html", data=data, errors=errors %}

        {% url_for [arg1=arg1], [arg2=arg2]... %}

        用法同 h.url_for():

        <a href="{% url_for controller="home", action="index" %}">Home</a>

        {% link_for text, [arg1=arg1], [arg2=arg2]... %}

        用法同 h.link_for():

        <li>{% link_for _("Home"), controller="home", action="index" %}</li>

        {% url_for_static path %}

        用法同 h.url_for_static():

        <script src="{% url_for_static "/javascript/home.js" %}"></script>




        CKAN 前端開發(v2.9): 概覽

        http://docs.ckan.org/en/2.9/contributing/frontend/index.html 

        前端的 stylesheet 採用 Less (系統需安裝 node.js ) 撰寫。

        檔案結構

        所有前端用到的檔案都放在 public 目錄下(ckan/lib/default/src/ckan/ckan/public/base)如下,檔名及目錄名稱都需小寫或用減號分隔:

        css/             --- Less 編譯後的 production  版 CSS 檔
          main.css
        less/            --- less 檔。vendor 的樣式檔放在 vendor 目錄,在 main.less 裡 include。
          main.less
          ckan.less
          ...
        javascript/     --- 建議使用 main.js 做為起始檔
          main.js
          utils.js
          components/
          ... 
        vendor/
        --- 存放外部相依檔,版本數字不能出現在檔名,應放在檔頭註解。 
        --- 函式庫需以函式庫名稱開頭。 
        --- 若相依檔有多個(如bootstrap檔)則整個目錄應用 distributed 方式處理。  
          jquery.js
          jquery.plugin.js
          underscore.js
          bootstrap.css
          ...

        Stylesheets

        所有樣式檔都以 Less 方式處理,開發前需先編譯:

        $ npm run watch

        以上指令會偵測所有 less 檔的修改並自動重建。(ctrl-c結束)。以下指令啟用偵錯模式,可看到sourcemaps:

        $ DEBUG=1 npm run watch

        樣式檔很多,主要有以下兩群:

        • main.less
          網站所有 dependancies、local 樣式,只排除某些情況下才載入的樣式,像是IE才用的 CSS  和只在某個網頁才顯示的外部 apps (如 recline)。
        • ckan.less
          所有 ckan 本身使用的樣式。

          JavaScript

          三部分:

          • Core (such as i18n, pub/sub and API clients)
            • Modules
            • Publisher/Subscriber
            • Client
            • i18n/Jed

          • Modules (small HTML components or widgets)
          • jQuery Plugins (very small reusable components)

          Module

          網頁上所有可互動的元件都應該是一個 module。在 HTML 元素裡加入 data-module 屬性/attribute  進行初始化:

          <select name="format" data-module="autocomplete"></select>

          這種作法的好處是讓它是一個小的可測試元件。所有全域物件應該透過 sandbox 傳入。

          用 global factory 建立新 modules,jQuery 及 Localisation 則透過 this.sandbox.jQuery 及 this.sandbox.translate()。

          ckan.module('my-module', function (jQuery) {
            return {
              initialize: function () {
                // Called when a module is created.
                // jQuery and translate are available here.
              },
              teardown: function () {
                // Called before a module is removed from the page.
              }
            }
          });

          Publisher/subscriber

          在 ckan.pubsub 下有一個簡單的 pub/sub module,透過 this.sandbox.publish/subscribe/unsubscribe,可在 module 間發佈/publish 訊息。

          module 間應透過 publish/subscribe 的方式溝通,讓 UI 上相關區域/area 做對應的刷新。

          ckan.module('language-picker', function (jQuery) {
            return {
              initialize: function () {
                var sandbox = this.sandbox;
                this.el.on('change', function () {
                  sandbox.publish('change:lang', this.selected);
                });
              }
            }
          });

          ckan.module('language-notifier', function (jQuery) {
            return {
              initialize: function () {
                this.sandbox.subscribe('change:lang', function (lang) {
                  alert('language is now ' + lang);
                });
              }
            }
          });

          Client

          module 不該用 jQuery.ajax() 呼叫 CKAN API,應該透過 client object。

          ckan.module('my-module', function (jQuery) {
            return {
              initialize: function () {
                this.sandbox.client.getCompletions(this.options.completionsUrl);
              }
            }
          });

          多國語系/Internationalization

          參考 Internationalizing strings in JavaScript code.

          生命週期/Life cycle

          CKAN module 在 dom ready 後初始化,ckan.module.initialize() 找出網頁中有 data-module  屬性的的 HTML 元素,試著建立對應的物件。

          <select name="format" data-module="autocomplete" data-module-key="id"></select>

          module 會依 HTML 元素中設定的 data-module-* 屬性建立對應的 sandbox 物件,建立後便呼叫 module 的 initialize() 初始化。

          module 應提供 teardown() 回復原始狀態。