Skip to content

Complete Type Hints and Add support for custom tags #13

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jul 10, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ These values are placed in the conf.py of your sphinx project.
* This is not required. Link to image to show.
* `ogp_type`
* This sets the ogp type attribute, for more information on the types available please take a look at https://ogp.me/#types. By default it is set to `website`, which should be fine for most use cases.
* `ogp_custom_meta_tags`
* This is not required. List of custom html snippets to insert.

## Example Config

Expand All @@ -45,4 +47,9 @@ ogp_site_url = "http://example.org/"
ogp_image = "http://example.org/image.png"
ogp_description_length = 300
ogp_type = "article"

ogp_custom_meta_tags = [
'<meta property="og:ignore_canonical" content="true" />',
]

```
22 changes: 14 additions & 8 deletions sphinxext/opengraph.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
from typing import Any, Dict, Iterable, Sequence, Tuple
from urllib.parse import urljoin
import docutils.nodes as nodes
import string
from html.parser import HTMLParser

import sphinx
from sphinx.application import Sphinx

DEFAULT_DESCRIPTION_LENGTH = 200

Expand All @@ -18,13 +20,13 @@ def __init__(self):
self.text_outside_tags = ""
self.level = 0

def handle_starttag(self, tag, attrs):
def handle_starttag(self, tag, attrs) -> None:
self.level += 1

def handle_endtag(self, tag):
def handle_endtag(self, tag) -> None:
self.level -= 1

def handle_data(self, data):
def handle_data(self, data) -> None:
self.text += data
if self.level == 0:
self.text_outside_tags += data
Expand All @@ -34,7 +36,7 @@ class OGMetadataCreatorVisitor(nodes.NodeVisitor):
Finds the title and creates a description from a doctree
"""

def __init__(self, desc_len, known_titles=None, document=None):
def __init__(self, desc_len: int, known_titles: Iterable[str] = None, document: nodes.document = None):

# Hack to prevent requirement for the doctree to be passed in.
# It's only used by doctree.walk(...) to print debug messages.
Expand Down Expand Up @@ -135,7 +137,7 @@ def make_tag(property: str, content: str) -> str:
return f'<meta property="{property}" content="{content}" />\n '


def get_tags(context, doctree, config):
def get_tags(context: Dict[str, Any], doctree: nodes.document, config: Dict[str, Any]) -> str:

# Set length of description
try:
Expand Down Expand Up @@ -182,20 +184,24 @@ def get_tags(context, doctree, config):
if image_url:
tags += make_tag("og:image", image_url)

# custom tags
tags += '\n'.join(config['ogp_custom_meta_tags'])

return tags


def html_page_context(app, pagename, templatename, context, doctree):
def html_page_context(app: Sphinx, pagename: str, templatename: str, context: Dict[str, Any], doctree: nodes.document) -> None:
if doctree:
context['metatags'] += get_tags(context, doctree, app.config)


def setup(app):
def setup(app: Sphinx) -> Dict[str, Any]:
app.add_config_value("ogp_site_url", None, "html")
app.add_config_value("ogp_description_length", DEFAULT_DESCRIPTION_LENGTH, "html")
app.add_config_value("ogp_image", None, "html")
app.add_config_value("ogp_type", "website", "html")
app.add_config_value("ogp_site_name", None, "html")
app.add_config_value("ogp_custom_meta_tags", [], "html")

app.connect('html-page-context', html_page_context)

Expand Down
12 changes: 12 additions & 0 deletions tests/roots/test-custom-tags/conf.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
extensions = ["sphinxext.opengraph"]

master_doc = "index"
exclude_patterns = ["_build"]

html_theme = "basic"

ogp_site_url = "http://example.org/"

ogp_custom_meta_tags = [
'<meta property="og:ignore_canonical" content="true" />',
]
1 change: 1 addition & 0 deletions tests/roots/test-custom-tags/index.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse at lorem ornare, fringilla massa nec, venenatis mi. Donec erat sapien, tincidunt nec rhoncus nec, scelerisque id diam. Orci varius natoque penatibus et magnis dis parturient mauris.
5 changes: 5 additions & 0 deletions tests/test_options.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,3 +86,8 @@ def test_nested_list_punctuation(og_meta_tags):
def test_skip_comments(og_meta_tags):
assert get_tag_content(og_meta_tags, "description") == "This is text."


@pytest.mark.sphinx("html", testroot="custom-tags")
def test_custom_tags(og_meta_tags):
assert get_tag_content(og_meta_tags, "ignore_canonical") == "true"