2025年2月19日 星期三

Odoo 產品 SKU 編碼最佳實務

摘譯 Best Way To Manage Product SKU in Odoo 。

SKU/Stock Keeping Unit 是追蹤產品的唯一識別碼。

1.標準化編碼規則

考慮管理上的一致性、可擴充性、方便編碼,可參考如下結構:

  • 類別/Category: APP-001 (for an Apparel category)
  • 品牌/Brand: NIKE-SHOE-10 (Nike shoes, size 10)
  • 供應商/Supplier: SUP123-PROD789 (Supplier and product reference combined)
  • 描述說明/Descriptive: TS-BL-S (T-Shirt, Blue, Small)

2.使用 Odoo Internal Reference 欄位

Odoo 透過 Internal Reference 欄位做為產品唯一識別碼

3.善用 產品變體/Product Variant

用產品變體管理同一種產品的客制品、子產品,每個產品變體也可以設定獨立的SKU。

4.自動產生 SKU

除了手動,Odoo 也可以自動為產品編碼,透過 Odoo Studio 或 custom scripts 自訂 SKU 範本,建立自動編碼規則。

也可整合 Barcode,讓 barcode 連動 SKU,方便產品識別。

5.確保 SKU 的唯一性

Odoo 的 Internal Reference 欄位會防止重複,但企業最好還是要有自己的運作法則確保 SKU 序號建立的邏輯。

6.在報表及篩選規則中使用 SKU 

Odoo 報表可以用 SKU 來篩選銷售、庫存、採購的報表資料。

7.啟用多倉 SKU 管理

Odoo 多倉/multi-warehouse 功能能透過 SKU,針對每個儲位/location、每次的調撥/stock transfer、補貨/restocking 提供庫存管理的資訊。

8.透過 SKU 整合電商及POS

9.定期盤點、清除SKU

一段時間後,因為斷貨或命名習慣的改變,一些SKU會過時,每隔一段時間就要移除無用的SKU,確保產品編碼的最佳狀態及一致性。

2025年2月18日 星期二

Odoo 用 Landed costs 加計產品成本:進口關稅、運費、再加工成本

可把以下都設為 Landed costs:


採購單中加入額外成本項目:



可以在為採購單付款時按下 "Create Landed Costs" 按鈕,也可以透過 Inventory app ‣ Operations ‣ Landed Costs:



如此,透過 Inventory app ‣ Reporting ‣ Valuation 便可看到庫存已加入這些額外成本:



再看產品資料,已自動反應產品成本:


順便提一下,若計算庫存成本,必須是能追蹤的產品:


在 Odoo 文件 Inventory operations by product type 的如下表格列出 追蹤/Tracked 功能 影響的庫存功能:

Inventory operation

Tracked

Untracked

Show on-hand quantity

Yes

No

Show forecasted quantity

Yes

No

Use reordering rules

Yes

No

Can be included in a purchase order

Yes

Yes

Use putaway rules

Yes

No

Can be manufactured, subcontracted, or used in another good’s BoM

Yes

Yes

Use inventory adjustments

Yes

No

Use inventory valuation

Yes

No

Create transfer

Yes

Yes

Use lot/serial number tracking

Yes

No

Can be placed in a kit

Yes

Yes

Can be placed in a package

Yes

Yes

Appears on inventory reports

Yes

No






2025年2月17日 星期一

Odoo 訂製品-產品變體/Product variant 及 屬性/attribute

為單一產品提供多種不同的屬性及選項,例如尺寸、顏色。

例如,服裝公司可對 T 恤設定以下變體/variant:

顏色:藍、紅、白、黑

尺碼:S、M、L、XL、XXL

屬性/attribute

在 Odoo 中,「T 恤」是產品範本,「顏色」及「尺碼」是屬性/attribute ,如此有 20 種不同產品變體:4 款 顏色 選項乘以 5 款 尺碼 選項。

每種款式變體 Odoo 系統都會記錄獨立的庫存數、銷售總額。


變體建立模式/Variant Creation Mode

何時建立新的產品變體?

  • 即時/Instantly:在產品範本新增屬性時,立即建立變體。
  • 動態/Dynamically: 有此變體產品的銷售訂單建立時,才會建立此產品變體。
  • 永不/Never:需自行手動建立產品變體。

產品變體一旦使用,建立模式便不能修改。

變體的影響

  • 條碼:每個變體可有獨立條碼、 SKU(庫存單位)。
  • 價格:每個變體可有獨立價格,為範本產品價格 加上 此變數屬性的各種額外收費。
    如:紅色襯衫的銷售價格為 $23,即:範本襯衫價格 $20,加紅色款式的 $3。
    可在價目表規則中設定計算方式,套用至產品範本或產品變體。
  • 庫存:庫存是每種單獨的產品變體進行盤點計數。範本產品的庫存反映的是所有變體的總和,但實際庫存數量是按各個變體計算的。
  • 圖片:每種產品變體都可以有自己的專屬圖片。
  • 產品範本的變更會自動套用至該產品的每種變體。

電子商務篩選器

客戶在網上商店購物時,是否要在前端看到這些屬性選項。


2024年12月30日 星期一

計量單位

計量單位類別

類別如下,每個類別有一個基準單位,如"長度和距離"是 m。


每類下可再細分,如"長度和距離"下可再分為毫米、公里等。也可自訂如: roll 250m。


類別若是"大於基準單位"則是基準單位乘上"比例",若是"小於基準單位"則是基準單位除以"比例"。
 


2024年12月25日 星期三

採購、訂單 交貨時間/Purchase lead times

每個商品的採購頁籤中可設定多個供應商,每個供應商的供貨價格及交貨時間,如下:


也可設定對客戶訂單的前置時間:

如此在 "報價單" 中便可自動推算廠商到貨時間:


及對客戶的訂單交貨時間:


2024年12月23日 星期一

Dropshipping

賣家不囤貨、不經手商品物流,只當中間人賺取差價。

每當客人下單,賣家就把訂單和發貨細節轉交批發商,直接發送給客戶。

啟用 Dropshipping

設定 Dropshipping 產品

可有多個供應商,清單順序在前面的優先供貨。





2022年5月18日 星期三

CKAN Route(2.9): add_ckan_admin_tab

https://github.com/ckan/ckan/blob/2.9/ckanext/example_iconfigurer/plugin.py

參考 CKAN Extensions Tutorial(v2.9):一個空的 CKAN extension,建立 ckanext-example_iconfigurer 擴充套件。

建立:ckanext-example_iconfigurer  

  1. 進入Python Virtual Environment:
    . /usr/lib/ckan/default/bin/activate
  2. 切換目錄
    cd /usr/lib/ckan/default/src 
  3. 執行 ckan generate extension,輸入:ckanext-example_iconfigurer。

撰寫 plugin 類別:ExampleIConfigurerPlugin

修改 ckanext-example_iconfigurer/ckanext/example_iconfigurer/plugin.py。參考完整程式,主要內容如下:

略...
import ckanext.example_iconfigurer.blueprint as blueprint

class ExampleIConfigurerPlugin(plugins.SingletonPlugin):
    略...

    plugins.implements(plugins.IConfigurer)
    plugins.implements(plugins.IBlueprint)

    # IConfigurer

    def update_config(self, config):
        # Add extension templates directory

        toolkit.add_template_directory(config, u'templates')
        # Add a new ckan-admin tabs for our extension
        toolkit.add_ckan_admin_tab(
            config, u'example_iconfigurer.config_one',
            u'My First Custom Config Tab'
        )
        toolkit.add_ckan_admin_tab(
            config, u'example_iconfigurer.config_two',
            u'My Second Custom Config Tab'
        )

撰寫 blueprint.py

參考完整程式,主要內容如下:

# encoding: utf-8

import ckan.lib.base as base
import ckan.lib.helpers as helpers
from flask import Blueprint
render = base.render

example_iconfigurer = Blueprint(u'example_iconfigurer', __name__)


def config_one():
    u'''Render the config template with the first custom title.'''

    return render(
        u'admin/myext_config.html',
        extra_vars={u'title': u'Custom Config Page A'}
    )


def config_two():
    u'''Render the config template with the second custom title.'''
    return render(
        u'admin/myext_config.html',
        extra_vars={u'title': u'Custom Config Page B'}
    )


def build_extra_admin_nav():
    u'''Return results of helpers.build_extra_admin_nav for testing.'''
    return helpers.build_extra_admin_nav()


example_iconfigurer.add_url_rule(
    u'/ckan-admin/myext_config_one', view_func=config_one
)
example_iconfigurer.add_url_rule(
    u'/ckan-admin/myext_config_two', view_func=config_two
)
example_iconfigurer.add_url_rule(
    u'/build_extra_admin_nav', view_func=build_extra_admin_nav
)

修改 setup.py:設定 entry_points

修改 ckanext-example_iconfigurer/setup.py 的 entry_points:

entry_points='''
        [ckan.plugins] 
        example_iconfigurer=ckanext.example_iconfigurer.plugin:ExampleIConfigurerPlugin

修改 ckan.ini:啟用 plugin

修改 /etc/ckan/default/ckan.ini。CKAN 的 extension plugins 必須加到 CKAN 設定檔的 ckan.plugins 中,CKAN 才會呼叫。

ckan.plugins = stats text_view 略... example_iconfigurer

安裝

  1. 進入Python Virtual Environment: 
    . /usr/lib/ckan/default/bin/activate
  2. 切換目錄:
    cd /usr/lib/ckan/default/src/example_iconfigurer
  3. 安裝 Plugin: 
    python setup.py develop
  4. 重啟 CKAN 服務:
    sudo supervisorctl restart ckan-uwsgi:*

測試

瀏覽 http://CKAN web site]/ckan-admin/ 可看到兩個新增的管理頁籤。




2022年5月17日 星期二

CKAN Route(2.9): Flask IBlueprint

參考 CKAN Extensions Tutorial(v2.9):一個空的 CKAN extension,建立 ckanext-example_flask_iblueprint 擴充套件。

建立:ckanext-example_flask_iblueprint  

  1. 進入Python Virtual Environment:
    . /usr/lib/ckan/default/bin/activate
  2. 切換目錄
    cd /usr/lib/ckan/default/src 
  3. 執行 ckan generate extension,輸入:ckanext-example_flask_iblueprint。

撰寫 plugin 類別:ExampleFlaskIBlueprintPlugin

修改 ckanext-example_flask_iblueprint/ckanext/example_flask_iblueprint/plugin.py。參考完整程式,主要內容如下:

class ExampleFlaskIBlueprintPlugin(p.SingletonPlugin):
    u'''
    An example IBlueprint plugin to demonstrate Flask routing from an
    extension.
    '''
    p.implements(p.IBlueprint)
    p.implements(p.IConfigurer)

    # IConfigurer

    def update_config(self, config):
        # Add extension templates directory
        p.toolkit.add_template_directory(config, u'templates')

    def get_blueprint(self):
        u'''Return a Flask Blueprint object to be registered by the app.'''

        # Create Blueprint for plugin
        blueprint = Blueprint(self.name, self.__module__)
        blueprint.template_folder = u'templates'
        # Add plugin url rules to Blueprint object
        rules = [
            (u'/hello_plugin', u'hello_plugin', hello_plugin),
            (u'/', u'home', override_flask_home),
            (u'/helper_not_here', u'helper_not_here', helper_not_here),
            (u'/helper', u'helper_here', helper_here),
            (u'/flask_request', u'flask_request', flask_request),
        ]
        for rule in rules:
            blueprint.add_url_rule(*rule)

        return blueprint

修改 setup.py:設定 entry_points

修改 ckanext-example_flask_iblueprint/setup.py 的 entry_points:

entry_points='''
        [ckan.plugins] 
        example_flask_iblueprint=ckanext.example_flask_iblueprint.plugin:ExampleFlaskIBlueprintPlugin

修改 ckan.ini:啟用 plugin

修改 /etc/ckan/default/ckan.ini。CKAN 的 extension plugins 必須加到 CKAN 設定檔的 ckan.plugins 中,CKAN 才會呼叫。

ckan.plugins = stats text_view 略... example_flask_iblueprint

安裝

  1. 進入Python Virtual Environment: 
    . /usr/lib/ckan/default/bin/activate
  2. 切換目錄:
    cd /usr/lib/ckan/default/src/example_flask_iblueprint
  3. 安裝 Plugin: 
    python setup.py develop
  4. 重啟 CKAN 服務:
    sudo supervisorctl restart ckan-uwsgi:*

測試

瀏覽 http://[CKAN web site] 下的 /, /hello_plugin, /helper, /helper_not_here, /flask_request 可看到對應的程式內容。

2022年5月12日 星期四

CKAN JavaScript Tutorial 2(v2.9): Webassets

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

CSS 檔等靜態檔案有兩種方式加入:簡單的 extra_public_paths 作法或是 Webassets。但 JavaScript module 就只能透過 Webassets。

Webasset 的好處是在 production 版中會自動最小化檔案、快取並打包/bundling,以減少下載時間,載入指定相依檔⋯⋯。

CKAN 只有 *.js、*.css 會以 Webasset 資源處理,其它的靜態檔(圖檔、PDF)要透過 extra_public_paths 方式處理。

建立: ckanext-example_theme

延續 CKAN Theming Tutorial 1(v2.9): 靜態檔案(圖片與CSS) 往下做。

建立 assets 目錄

把 example_theme.css 改放到 assets 目錄下:

ckanext-example_theme/
  ckanext/
    example_theme/
      public/
        promoted-image.jpg
      assets/
        example_theme.css
        webassets.yml

另外再加一個 webassets.yml ,內容如下:

example_theme:
  output: example_theme/example_theme.css
  contents:
    - example_theme.css

修改 plugin.py

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

# encoding: utf-8

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

def most_popular_groups():
    略⋯⋯

class ExampleThemePlugin(plugins.SingletonPlugin):
    略⋯⋯

    def update_config(self, config):
        略⋯⋯

        # Register this plugin's assets directory with CKAN.
        # Here, 'assets' is the path to the webassets directory
        # (relative to this plugin.py file), and 'example_theme' is the name
        # that we'll use to refer to this assets directory from CKAN
        # templates.
        toolkit.add_resource('assets', 'example_theme')
  • toolkit.add_resource 的兩個參數:
    • assets: webassets 所在目錄(相對於plugin.py的路徑)
    • example_theme: 在 CKAN template 中存取此 assets 目錄的名稱

在 templates 中使用 {% asset %}

編輯 ckanext-example_theme/ckanext/example_theme/templates/base.html,在其中以 Jinja2 的{% asset %} 取代<link>  匯入檔案,如下:

{% ckan_extends %}

{% block styles %}
  {{ super() }}

  {# Import example_theme.css using Webassets.  'example_theme/' is
    the name that the example_theme/fanstatic directory was registered
    with when the toolkit.add_resource() function was called.
    'example_theme' is the name to the Webassets bundle file,
    registered inside webassets.yml file. #}
  {% asset 'example_theme/example_theme' %}

{% endblock %}

所有 template 都可用 {% asset %},Webassets 會加入需要的 <style> 、 <script>  來 include CSS 及JavaScript檔案,但最好把他們集中在 Jinja2 的  styles、scripts block.

Assets 不會在 {% asset %} 出現那行被 include。

用一個設定檔設定 Webassets 如何處理每個 asset 檔(是否打包/bundle,include的順序,include 檔要放在網頁的最前面還是最後面,檔案間的相依性...),參考:Assets。

安裝

  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] 的網頁原始碼,在HTML的 <head>...</head> 可發現:

<link href="/webassets/webassets-external/2dce0ddda2882168f0c12c639a912e24_example_theme.css" rel="stylesheet"/>

2022年5月8日 星期日

CAKN 偵錯: flask_debugtoolbar

  1. 啟動 Python 虛擬環境
    . /usr/lib/ckan/default/bin/activate
  2. 安裝 flask_debugtoolbar
    pip install flask_debugtoolbar
  3. 開啟偵錯模式
    vi /etc/ckan/default/ckan.ini
    debug = true
  4. 重啟 CKAN
    sudo supervisorctl restart ckan-uwsgi:*
  • 若有錯檢視 uwsgi.ERR
    cat /etc/ckan/default/uwsgi.ERR


2022年5月6日 星期五

CKAN Templates Tutorial 9(v2.9): 存取自訂的 config 設定

http://docs.ckan.org/en/2.9/theming/templates.html#accessing-custom-config-settings-from-templates

template 裡的 app_globals 不是所有 CKAN config 設定都能存取,自訂的 config 設定無法取得,但透過 helper function 就可以。

參考:Using custom config settings in extensions。

延續 上個 CKAN templates CSS tutorial。

新增自訂 config 設定

如下 show_most_popular_groups 設定,決定首頁是否顯示最受歡迎群組。

修改 extension 根目錄下的 plugin.py,新增 helper function 存取自訂的 show_most_popular_groups 設定:

# encoding: utf-8


import ckan.plugins as plugins
import ckan.plugins.toolkit as toolkit
from ckan.common import config


def show_most_popular_groups():
    '''Return the value of the most_popular_groups config setting.

    To enable showing the most popular groups, add this line to the
    [app:main] section of your CKAN config file::

      ckan.example_theme.show_most_popular_groups = True

    Returns ``False`` by default, if the setting is not in the config file.

    :rtype: bool

    '''
    value = config.get('ckan.example_theme.show_most_popular_groups', False)
    value = toolkit.asbool(value)
    return value

略⋯⋯

class ExampleThemePlugin(plugins.SingletonPlugin):
    略⋯⋯

    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,
                'example_theme_show_most_popular_groups':
                show_most_popular_groups,
                }

extension 加入的 config 設定名稱要以 extension 名稱開頭,以避免與其他 extension 或 CKAN 內建設定衝突(參考 Avoid name clashes)。

在 layout1.html 中呼叫自訂 helper function

修改 templates/home/layout1.html 如下:

{% ckan_extends %}

略⋯⋯

{# Show the most popular groups if the show_most_popular_groups config setting
   is True, otherwise call the super block. #}
{% block featured_organization %}
<p>example_theme_show_most_popular_groups: [{{h.example_theme_show_most_popular_groups()}}]</p>
  {% if h.example_theme_show_most_popular_groups() %}
    {% snippet 'snippets/example_theme_most_popular_groups.html' %}
  {% else %}
    {{ super() }}
  {% endif %}
{% endblock %}

修改 ckan.ini 設定

/etc/ckan/default/ckan.ini

[app:main]
## example_theme
ckan.example_theme.show_most_popular_groups = False

安裝

  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


CKAN Templates Tutorial 8(v2.9): CSS class

http://docs.ckan.org/en/2.9/theming/templates.html#html-tags-and-css-classes

CKAN 使用的 CSS class 來自:

  1. Bootstrap 3.3.7
    這個版本 Bootstrap 的 HTML, CSS, JavaScript 都可在 CKAN 中使用
  2. CKAN 的 development primer page
    CKAN 網站下的 /testing/primer

調整 snippet 裡的 CSS class

修改 ckanext-example_theme/ckanext/example_theme/templates/snippets/example_theme_most_popular_groups.html 如下:

{#

Renders a list of the site's most popular groups.

groups - the list of groups to render

#}
<div class="box">
  <header class="module-heading">
    <h3>Most popular groups</h3>
  </header>
  <section class="module-content">
    <ul class="unstyled">
      {% for group in groups %}
      <li>
        <a href="{{ h.url_for('group_read', action='read', id=group.name) }}">
          <h3>{{ group.display_name }}</h3>
        </a>
        {% if group.description %}
          <p>
            {{ h.markdown_extract(group.description, extract_length=80) }}
          </p>
        {% else %}
          <p>{{ _('This group has no description') }}</p>
        {% endif %}
        {% if group.package_count %}
          <strong>{{ ungettext('{num} Dataset', '{num} Datasets', group.package_count).format(num=group.package_count) }}</strong>
        {% else %}
          <span>{{ _('0 Datasets') }}</span>
        {% endif %}
      </li>
    {% endfor %}
 </ul>
  <section>
</div>

以上加入:

  • 把程式碼放進
    • <div class="box">
    • <header class="module-heading">
    • <section class="module-content">
  • 用 Bootstrap 的 class="unstyled" 移除 <ul> 前的黑點

調整 layout1.html 的 CSS class

修改 ckanext-example_theme/ckanext/example_theme/templates/home/layout1.html 如下:

{% ckan_extends %}

{% block featured_group %}
  <div class="box">
    <header class="module-heading">
      <h3>Recent activity</h3>
    </header>
    <div class="module-content">
    <ul>
        {% for stream in h.recently_changed_packages_activity_stream(limit=4) %}
            <li>stream id: {{ stream.id }}</li>
        {% endfor %}
    </ul>
    </div>
  </div>

{% endblock %}

{% block featured_organization %}
  {% snippet 'snippets/example_theme_most_popular_groups.html',
             groups=h.example_theme_most_popular_groups()  %}
{% endblock %}


重新檢視網頁:






CKAN Templates Tutorial 7(v2.9): 自訂 snippet

http://docs.ckan.org/en/2.9/theming/templates.html#adding-your-own-template-snippets

延續 上個 CKAN templates snippet tutorial,plugin 只要在它的 templates/snippets 目錄下加檔案即可自訂 snippet。

以下撰寫一個 snippet 來顯示最受歡迎群組。


在 templates/snippets 目錄下新增 snippet

建立目錄 ckanext-example_theme/ckanext/example_theme/templates/snippets,並在其下加入一個檔案:example_theme_most_popular_groups.html ,內容如下:

{#

Renders a list of the site's most popular groups.

groups - the list of groups to render

#}
<h3>熱門群組(自訂snippet)</h3>
<ul>
  {% for group in groups %}
    <li>
      <a href="{{ h.url_for('group_read', action='read', id=group.name) }}">
        <h3>{{ group.display_name }}</h3>
      </a>
      {% if group.description %}
        <p>
          {{ h.markdown_extract(group.description, extract_length=80) }}
        </p>
      {% else %}
        <p>{{ _('This group has no description') }}</p>
      {% endif %}
      {% if group.package_count %}
        <strong>{{ ungettext('{num} Dataset', '{num} Datasets', group.package_count).format(num=group.package_count) }}</strong>
      {% else %}
        <span>{{ _('0 Datasets') }}</span>
      {% endif %}
    </li>
  {% endfor %}
</ul>

  • snippet 檔最開頭需以 docstring 描述需傳入的參數。在這個例子裡是:groups。
  • 呼叫 url_for() 為每個 group 名稱產生超連結至群組頁面
  • 若群組有 description 呼叫 markdown_extract() 產生其內容,若無則呼叫 _() 把 'This group has no description' 訊息翻譯使用者瀏覽器對應的語言。
  • 呼叫 ungettext() 顯示群組的資料集數(翻譯成對應的複數表示方式)。
  • 群組屬性/group attributes 如: {{ group.name }}, {{ group.display_name }}, {{ group.description }}, {{ group.package_count }},及其他 CKAN 物件(packages/datasets, organizations, users…) 屬性可透過 CKAN API 讀取,如 group_show()。


修改 templates/home/layout1.html

如下:

{% ckan_extends %}

{% block featured_group %}
  {{ h.recently_changed_packages_activity_stream(limit=4) }}
{% endblock %}

{% block featured_organization %}
  {% snippet 'snippets/example_theme_most_popular_groups.html',
             groups=h.example_theme_most_popular_groups()  %}
{% endblock %}

重啟 CKAN,再次瀏覽網頁可看到:

覆寫預設 snippet

若 plugin 加入的 snippet 名稱與 CKAN 預設 snippet 同名,則 plugin 的 snippet 會覆寫預設 snippet,無論是否有使用它。

若兩個 plugins 有同名 snippet 便會互相覆蓋。為避免這個問題,snippet 檔名最好以它的 extension 名稱開頭,如:snippets/example_theme_*.html。

snippet 「不能」存取 template 全域環境變數 c ( Variables and functions available to templates). 但可以存取:

  • h
  • app_globals
  • request
  • 其他父 template 透過 {% snippet %} 呼叫時傳入的參數

CKAN Templates Tutorial 6(v2.9): snippet

http://docs.ckan.org/en/2.9/theming/templates.html#template-snippets

Template snippets 是一小段/snippet template code,如同 helper functions,可在 template 裡呼叫。CKAN 在 ckan/templates/ 目錄下,可看到如:ckan/templates/snippets/ 及 ckan/templates/package/snippets/。

如下 ckan/templates/group/snippets/group_list.html 這個 snippet,可協助很好地顯示 group 清單。它裡面又呼叫了另一段 snippet- group/snippets/group_item.html:

{#
Display a grid of group items.

groups - A list of groups.

Example:

    {% snippet "group/snippets/group_list.html" %}

#}
{% block group_list %}
<ul class="media-grid" data-module="media-grid">
{% block group_list_inner %}
  {% for group in groups %}
    {% snippet "group/snippets/group_item.html", group=group, position=loop.index %}
  {% endfor %}
  {% endblock %}
</ul>
{% endblock %}


修改 layout1.html

ckanext-example_theme/ckanext/example_theme/templates/home/layout1.html:

⋯⋯略

{% block featured_organization %}

  <h3>熱門群組</h3>
  {# Call the group_list.html snippet. #}
  {% snippet 'group/snippets/group_list.html',
             groups=h.example_theme_most_popular_groups() %}

{% endblock %}

如上程式,傳了兩個參數給 {% snippet %} tag:

  • 'group/snippets/group_list.html'
    要呼叫的 template snippet
  • groups=h.example_theme_most_popular_groups()

在 snippet 檔名後面,可傳入任意個參數給 snippet 裡的程式,變成 snippet 裡的全域變數。每個 snippet 檔應該在最前面的 docstring 註解它需要傳入那些參數。

更新後,首頁右下區塊結果如下:




2022年5月5日 星期四

CKAN Templates Tutorial 5(v2.9): Template helper functions

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

結果如下:






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]/