SlideShare uses cookies to improve functionality and performance, and to provide you with relevant advertising. If you continue browsing the site, you agree to the use of cookies on this website. See our User Agreement and Privacy Policy.
SlideShare uses cookies to improve functionality and performance, and to provide you with relevant advertising. If you continue browsing the site, you agree to the use of cookies on this website. See our Privacy Policy and User Agreement for details.
Successfully reported this slideshow.
Activate your 14 day free trial to unlock unlimited reading.
Sphinx customization for OGP support at SphinxCon JP 2018
24.
フック関数の動作 (1/4)
html-page-context イベントでogpタグをレンダリングする
ためにdoctreeからデータを集めます。
doctreeはドキュメント(1ファイル)のAST (Abstract Syntax
Tree: 抽象構文木)です。Sphinx拡張はVisitorパターンで
doctreeからデータを集められます。
24
def html_page_context(app, pagename, templatename,
context, doctree):
if not doctree:
return
# walk over the `doctree` structure using visitor pattern
ogtag.py
Spec: http://www.sphinx-doc.org/en/master/extdev/appapi.html#event-html-page-context
25.
フック関数の動作 (2/4)
25
og:image タグのための画像をdoctreeから探します。
imageノードというのをdoctreeから探して1つめを使ってま
す。
class Visitor:
def dispatch_visit(self, node):
…
# collect first image node
if isinstance(node, nodes.image):
self.images.append(node)
…
def get_og_image_url(self, page_url):
if self.images:
return urljoin(page_url, self.images[0]['uri'])
else:
return None
Spec: http://docutils.sourceforge.net/docs/ref/doctree.html
ogtag.py
26.
フック関数の動作 (3/4)
og:descriptionにはページの概要文のためのテキストを持
たせます。この拡張では3セクション分のテキストを集めま
した
26
class Visitor:
def dispatch_visit(self, node):
…
# collect page text from the first 3 sections
if self.n_sections < 3:
# collect text elements
if isinstance(node, nodes.paragraph):
self.text_list.append(node.astext())
…
def get_og_description(self):
text = ' '.join(self.text_list)
if len(text) > 200:
text = text[:197] + '...'
return text
Spec: http://docutils.sourceforge.net/docs/ref/doctree.html
ogtag.py
29.
make html
29
import sys
import os
sys.path.append(os.path.abspath('_ext')) # path where ogtag.py
extensions = {
‘ogtag’, # python module names of extension
}
og_site_url = 'http://sphinx-users.jp/' # base url path for og:url tag
og_twitter_site = '@sphinxjp' # twitter account for twitter:site.
conf.py
$ make html
…
Build finished. The HTML pages are in _build/html.
$ <deploy _build/html>
command-line