2022年5月5日 星期四

CKAN v2.9 templates 4: {% ckan_extends %} {% block %} {{ super() }}

{% ckan_extends %}

用 Jinja 的 {% ckan_extends %} 可讓自訂 template 「擴充」預設內容,而不是取代它。

修改 index.html

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

{% ckan_extends %}

重新瀏覽 CKAN 首頁,自訂 index.html 裡的 {% ckan_extends %} 告訴 CKAN 先執行原本的 home/index.html。

{% block %}

Jinja templates 中可嵌入 block 讓其它 templates 取代其內容,如 CKAN 預設 /usr/lib/ckan/default/src/ckan/ckan/templates/home/layout1.html:


<div role="main">
  <div class="main hero">
    <div class="container">
      <div class="row row1">
        <div class="col-md-6 col1">
          {% block promoted %}
            {% snippet 'home/snippets/promoted.html' %}
          {% endblock %}
        </div>
        <div class="col-md-6 col2">
          {% block search %}
            {% snippet 'home/snippets/search.html' %}
          {% endblock %}
        </div>
      </div>
    </div>
  </div>
  <div class="main">
    <div class="container">
      <div class="row row2">
        <div class="col-md-6 col1">
          {# Note: this featured_group block is used as an example in the theming
             tutorial in the docs! If you change this code, be sure to check
             whether you need to update the docs. #}
          {# Start template block example. #}
          {% block featured_group %}
            {% snippet 'home/snippets/featured_group.html' %}
          {% endblock %}
          {# End template block example. #}
        </div>
        <div class="col-md-6 col2">
          {% block featured_organization %}
            {% snippet 'home/snippets/featured_organization.html' %}
          {% endblock %}
        </div>
      </div>
    </div>
  </div>
</div>

CKAN 支援不同的layout: layout1, layout2, layout3 等。由 sysadmin 在 admin 頁設定。假設使用第一個 layout1.html。

以 {% ckan_extends %} 擴充 CKAN 預設的 template,可用 {% block %} 取代預設 template 中的任何 block。

新增 layout1.html

建立 ckanext-example_theme/ckanext/example_theme/templates/home/layout1.html ,內容如下:

{% ckan_extends %}

{% block featured_group %}
  取代原本的 featured_group: Hello block world!
{% endblock %}

這個檔案擴充原本的 layout1.html,覆寫其中的 featured_group block。

重啟 web server,瀏覽 CKAN 首頁,可看到 featured_group 區塊已被取代為 Hello block world!,但其它內容都沒有動。


{{ super() }}

{{ super() }} 可在 block 加入內容,而不是取代它。

修改:layout1.html

{% ckan_extends %}

{% block featured_group %}
    <p>這段文字會出現在 <code>featured_group</code> block 上方</p>      
    {{ super() }}
    <p>這段文字會出現在 <code>featured_group</code> block 下方</p>
{% endblock %}

以上 block 執行時,{{ super() }} 會被 parent block 的內容取代。



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>