加入參考域¶
本教學的目標是說明角色、指令和域。完成後,我們將能夠使用此擴展來描述食譜,並從文件中的其他地方參考該食譜。
注意
本教學基於最初發表在 opensource.com 上的指南,並在此處提供,已獲得原始作者的許可。
概觀¶
我們希望擴展將以下內容添加到 Sphinx
一個
recipe
指令,包含一些描述食譜步驟的內容,以及一個:contains:
選項,用於突出顯示食譜的主要成分。一個
ref
角色,提供對食譜本身的交叉引用。一個
recipe
域,允許我們將上述角色和域以及索引之類的東西結合在一起。
為此,我們需要將以下元素添加到 Sphinx
一個名為
recipe
的新指令新的索引,允許我們參考成分和食譜
一個名為
recipe
的新域,它將包含recipe
指令和ref
角色
先決條件¶
我們需要與 之前的擴展 中相同的設定。這次,我們將把我們的擴展放在一個名為 recipe.py
的檔案中。
以下是您可能獲得的資料夾結構範例
└── source
├── _ext
│ └── recipe.py
├── conf.py
└── index.rst
撰寫擴展¶
開啟 recipe.py
並貼上以下程式碼,我們將在稍後詳細解釋所有內容
1from collections import defaultdict
2
3from docutils.parsers.rst import directives
4
5from sphinx import addnodes
6from sphinx.application import Sphinx
7from sphinx.directives import ObjectDescription
8from sphinx.domains import Domain, Index
9from sphinx.roles import XRefRole
10from sphinx.util.nodes import make_refnode
11from sphinx.util.typing import ExtensionMetadata
12
13
14class RecipeDirective(ObjectDescription):
15 """A custom directive that describes a recipe."""
16
17 has_content = True
18 required_arguments = 1
19 option_spec = {
20 'contains': directives.unchanged_required,
21 }
22
23 def handle_signature(self, sig, signode):
24 signode += addnodes.desc_name(text=sig)
25 return sig
26
27 def add_target_and_index(self, name_cls, sig, signode):
28 signode['ids'].append('recipe' + '-' + sig)
29 if 'contains' in self.options:
30 ingredients = [x.strip() for x in self.options.get('contains').split(',')]
31
32 recipes = self.env.get_domain('recipe')
33 recipes.add_recipe(sig, ingredients)
34
35
36class IngredientIndex(Index):
37 """A custom index that creates an ingredient matrix."""
38
39 name = 'ingredient'
40 localname = 'Ingredient Index'
41 shortname = 'Ingredient'
42
43 def generate(self, docnames=None):
44 content = defaultdict(list)
45
46 recipes = {
47 name: (dispname, typ, docname, anchor)
48 for name, dispname, typ, docname, anchor, _ in self.domain.get_objects()
49 }
50 recipe_ingredients = self.domain.data['recipe_ingredients']
51 ingredient_recipes = defaultdict(list)
52
53 # flip from recipe_ingredients to ingredient_recipes
54 for recipe_name, ingredients in recipe_ingredients.items():
55 for ingredient in ingredients:
56 ingredient_recipes[ingredient].append(recipe_name)
57
58 # convert the mapping of ingredient to recipes to produce the expected
59 # output, shown below, using the ingredient name as a key to group
60 #
61 # name, subtype, docname, anchor, extra, qualifier, description
62 for ingredient, recipe_names in ingredient_recipes.items():
63 for recipe_name in recipe_names:
64 dispname, typ, docname, anchor = recipes[recipe_name]
65 content[ingredient].append((
66 dispname,
67 0,
68 docname,
69 anchor,
70 docname,
71 '',
72 typ,
73 ))
74
75 # convert the dict to the sorted list of tuples expected
76 content = sorted(content.items())
77
78 return content, True
79
80
81class RecipeIndex(Index):
82 """A custom index that creates an recipe matrix."""
83
84 name = 'recipe'
85 localname = 'Recipe Index'
86 shortname = 'Recipe'
87
88 def generate(self, docnames=None):
89 content = defaultdict(list)
90
91 # sort the list of recipes in alphabetical order
92 recipes = self.domain.get_objects()
93 recipes = sorted(recipes, key=lambda recipe: recipe[0])
94
95 # generate the expected output, shown below, from the above using the
96 # first letter of the recipe as a key to group thing
97 #
98 # name, subtype, docname, anchor, extra, qualifier, description
99 for _name, dispname, typ, docname, anchor, _priority in recipes:
100 content[dispname[0].lower()].append((
101 dispname,
102 0,
103 docname,
104 anchor,
105 docname,
106 '',
107 typ,
108 ))
109
110 # convert the dict to the sorted list of tuples expected
111 content = sorted(content.items())
112
113 return content, True
114
115
116class RecipeDomain(Domain):
117 name = 'recipe'
118 label = 'Recipe Sample'
119 roles = {
120 'ref': XRefRole(),
121 }
122 directives = {
123 'recipe': RecipeDirective,
124 }
125 indices = {
126 RecipeIndex,
127 IngredientIndex,
128 }
129 initial_data = {
130 'recipes': [], # object list
131 'recipe_ingredients': {}, # name -> object
132 }
133 data_version = 0
134
135 def get_full_qualified_name(self, node):
136 return f'recipe.{node.arguments[0]}'
137
138 def get_objects(self):
139 yield from self.data['recipes']
140
141 def resolve_xref(self, env, fromdocname, builder, typ, target, node, contnode):
142 match = [
143 (docname, anchor)
144 for name, sig, typ, docname, anchor, prio in self.get_objects()
145 if sig == target
146 ]
147
148 if len(match) > 0:
149 todocname = match[0][0]
150 targ = match[0][1]
151
152 return make_refnode(builder, fromdocname, todocname, targ, contnode, targ)
153 else:
154 print('Awww, found nothing')
155 return None
156
157 def add_recipe(self, signature, ingredients):
158 """Add a new recipe to the domain."""
159 name = f'recipe.{signature}'
160 anchor = f'recipe-{signature}'
161
162 self.data['recipe_ingredients'][name] = ingredients
163 # name, dispname, type, docname, anchor, priority
164 self.data['recipes'].append((
165 name,
166 signature,
167 'Recipe',
168 self.env.docname,
169 anchor,
170 0,
171 ))
172
173
174def setup(app: Sphinx) -> ExtensionMetadata:
175 app.add_domain(RecipeDomain)
176
177 return {
178 'version': '0.1',
179 'parallel_read_safe': True,
180 'parallel_write_safe': True,
181 }
讓我們逐步查看此擴展的每個部分,以解釋正在發生的事情。
指令類別
首先要檢查的是 RecipeDirective
指令
1class RecipeDirective(ObjectDescription):
2 """A custom directive that describes a recipe."""
3
4 has_content = True
5 required_arguments = 1
6 option_spec = {
7 'contains': directives.unchanged_required,
8 }
9
10 def handle_signature(self, sig, signode):
11 signode += addnodes.desc_name(text=sig)
12 return sig
13
14 def add_target_and_index(self, name_cls, sig, signode):
15 signode['ids'].append('recipe' + '-' + sig)
16 if 'contains' in self.options:
17 ingredients = [x.strip() for x in self.options.get('contains').split(',')]
18
19 recipes = self.env.get_domain('recipe')
20 recipes.add_recipe(sig, ingredients)
與 使用角色和指令擴展語法 和 擴展建置流程 不同,此指令不衍生自 docutils.parsers.rst.Directive
並且未定義 run
方法。相反,它衍生自 sphinx.directives.ObjectDescription
並定義了 handle_signature
和 add_target_and_index
方法。這是因為 ObjectDescription
是一個特殊用途的指令,旨在描述類別、函數或在我們的例子中是食譜之類的東西。更具體地說,handle_signature
實作了指令簽章的解析,並將物件的名稱和類型傳遞給其父類別,而 add_target_and_index
則為此節點新增目標(用於連結)和索引項目。
我們也看到此指令定義了 has_content
、required_arguments
和 option_spec
。與 先前的教學 中新增的 TodoDirective
指令不同,此指令除了主體中巢狀的 reStructuredText 之外,還接受單一引數(食譜名稱)和一個選項 contains
。
索引類別
1class IngredientIndex(Index):
2 """A custom index that creates an ingredient matrix."""
3
4 name = 'ingredient'
5 localname = 'Ingredient Index'
6 shortname = 'Ingredient'
7
8 def generate(self, docnames=None):
9 content = defaultdict(list)
10
11 recipes = {
12 name: (dispname, typ, docname, anchor)
13 for name, dispname, typ, docname, anchor, _ in self.domain.get_objects()
14 }
15 recipe_ingredients = self.domain.data['recipe_ingredients']
16 ingredient_recipes = defaultdict(list)
17
18 # flip from recipe_ingredients to ingredient_recipes
19 for recipe_name, ingredients in recipe_ingredients.items():
20 for ingredient in ingredients:
21 ingredient_recipes[ingredient].append(recipe_name)
22
23 # convert the mapping of ingredient to recipes to produce the expected
24 # output, shown below, using the ingredient name as a key to group
25 #
26 # name, subtype, docname, anchor, extra, qualifier, description
27 for ingredient, recipe_names in ingredient_recipes.items():
28 for recipe_name in recipe_names:
29 dispname, typ, docname, anchor = recipes[recipe_name]
30 content[ingredient].append((
31 dispname,
32 0,
33 docname,
34 anchor,
35 docname,
36 '',
37 typ,
38 ))
39
40 # convert the dict to the sorted list of tuples expected
41 content = sorted(content.items())
42
43 return content, True
1class RecipeIndex(Index):
2 """A custom index that creates an recipe matrix."""
3
4 name = 'recipe'
5 localname = 'Recipe Index'
6 shortname = 'Recipe'
7
8 def generate(self, docnames=None):
9 content = defaultdict(list)
10
11 # sort the list of recipes in alphabetical order
12 recipes = self.domain.get_objects()
13 recipes = sorted(recipes, key=lambda recipe: recipe[0])
14
15 # generate the expected output, shown below, from the above using the
16 # first letter of the recipe as a key to group thing
17 #
18 # name, subtype, docname, anchor, extra, qualifier, description
19 for _name, dispname, typ, docname, anchor, _priority in recipes:
20 content[dispname[0].lower()].append((
21 dispname,
22 0,
23 docname,
24 anchor,
25 docname,
26 '',
27 typ,
28 ))
29
30 # convert the dict to the sorted list of tuples expected
31 content = sorted(content.items())
32
33 return content, True
IngredientIndex
和 RecipeIndex
都衍生自 Index
。它們實作自訂邏輯以產生定義索引的值元組。請注意,RecipeIndex
是一個簡單的索引,只有一個項目。擴展它以涵蓋更多物件類型尚未成為程式碼的一部分。
這兩個索引都使用方法 Index.generate()
來完成它們的工作。此方法結合了我們域中的資訊,對其進行排序,並將其以 Sphinx 將接受的列表結構返回。這看起來可能很複雜,但實際上它只是一個元組列表,例如 ('tomato', 'TomatoSoup', 'test', 'rec-TomatoSoup',...)
。有關此 API 的更多資訊,請參閱 域 API 指南。
這些索引頁面可以使用 ref
角色通過組合域名稱和索引 name
值來參考。例如,RecipeIndex
可以使用 :ref:`recipe-recipe`
參考,而 IngredientIndex
可以使用 :ref:`recipe-ingredient`
參考。
域
Sphinx 域是一個特殊的容器,它將角色、指令和索引等其他事物結合在一起。讓我們看看我們在這裡建立的域。
1class RecipeDomain(Domain):
2 name = 'recipe'
3 label = 'Recipe Sample'
4 roles = {
5 'ref': XRefRole(),
6 }
7 directives = {
8 'recipe': RecipeDirective,
9 }
10 indices = {
11 RecipeIndex,
12 IngredientIndex,
13 }
14 initial_data = {
15 'recipes': [], # object list
16 'recipe_ingredients': {}, # name -> object
17 }
18 data_version = 0
19
20 def get_full_qualified_name(self, node):
21 return f'recipe.{node.arguments[0]}'
22
23 def get_objects(self):
24 yield from self.data['recipes']
25
26 def resolve_xref(self, env, fromdocname, builder, typ, target, node, contnode):
27 match = [
28 (docname, anchor)
29 for name, sig, typ, docname, anchor, prio in self.get_objects()
30 if sig == target
31 ]
32
33 if len(match) > 0:
34 todocname = match[0][0]
35 targ = match[0][1]
36
37 return make_refnode(builder, fromdocname, todocname, targ, contnode, targ)
38 else:
39 print('Awww, found nothing')
40 return None
41
42 def add_recipe(self, signature, ingredients):
43 """Add a new recipe to the domain."""
44 name = f'recipe.{signature}'
45 anchor = f'recipe-{signature}'
46
47 self.data['recipe_ingredients'][name] = ingredients
48 # name, dispname, type, docname, anchor, priority
49 self.data['recipes'].append((
50 name,
51 signature,
52 'Recipe',
53 self.env.docname,
54 anchor,
55 0,
56 ))
關於此 recipe
域和一般域,有一些有趣的事情需要注意。首先,我們實際上是在這裡註冊我們的指令、角色和索引,通過 directives
、roles
和 indices
屬性,而不是稍後在 setup
中通過呼叫。我們還可以注意到,我們實際上並未定義自訂角色,而是重複使用 sphinx.roles.XRefRole
角色並定義 sphinx.domains.Domain.resolve_xref
方法。此方法接受兩個引數,typ
和 target
,它們分別指交叉引用類型及其目標名稱。我們將使用 target
從我們域的 recipes
中解析我們的目標,因為我們目前只有一種節點類型。
繼續,我們可以看到我們已經定義了 initial_data
。initial_data
中定義的值將作為域的初始資料複製到 env.domaindata[domain_name]
,域實例可以通過 self.data
訪問它。我們看到我們在 initial_data
中定義了兩個項目:recipes
和 recipe_ingredients
。每個都包含所有已定義物件的列表(即所有食譜)和一個雜湊,該雜湊將規範成分名稱映射到物件列表。我們命名物件的方式在我們的擴展中很常見,並且在 get_full_qualified_name
方法中定義。對於建立的每個物件,規範名稱是 recipe.<recipename>
,其中 <recipename>
是文件撰寫者給物件(食譜)的名稱。這使擴展能夠使用共享相同名稱的不同物件類型。擁有規範名稱和物件的中心位置是一個巨大的優勢。我們的索引和交叉引用程式碼都使用了此功能。
setup
函數
一如既往,setup
函數是必需的,用於將我們擴展的各個部分掛鉤到 Sphinx 中。讓我們看看此擴展的 setup
函數。
1def setup(app: Sphinx) -> ExtensionMetadata:
2 app.add_domain(RecipeDomain)
3
4 return {
5 'version': '0.1',
6 'parallel_read_safe': True,
7 'parallel_write_safe': True,
8 }
這看起來與我們習慣看到的略有不同。沒有呼叫 add_directive()
甚至 add_role()
。相反,我們只有單次呼叫 add_domain()
,然後是一些 標準域 的初始化。這是因為我們已經將我們的指令、角色和索引註冊為指令本身的一部分。
使用擴展¶
您現在可以在整個專案中使用擴展。例如
Joe's Recipes
=============
Below are a collection of my favourite recipes. I highly recommend the
:recipe:ref:`TomatoSoup` recipe in particular!
.. toctree::
tomato-soup
The recipe contains `tomato` and `cilantro`.
.. recipe:recipe:: TomatoSoup
:contains: tomato, cilantro, salt, pepper
This recipe is a tasty tomato soup, combine all ingredients
and cook.
需要注意的重要事項是使用 :recipe:ref:
角色來交叉引用實際在其他地方定義的食譜(使用 :recipe:recipe:
指令)。
延伸閱讀¶
如需更多資訊,請參閱 docutils 文件和 Sphinx API。
如果您希望在多個專案或與他人共享您的擴展,請查看 第三方擴展 部分。