Skip to content

Commit

Permalink
tiny convenience func to encode key/val pairs in nodes (#76)
Browse files Browse the repository at this point in the history
  • Loading branch information
choldgraf committed Feb 22, 2020
1 parent 334f15f commit e463e0a
Showing 1 changed file with 20 additions and 12 deletions.
32 changes: 20 additions & 12 deletions myst_parser/docutils_renderer.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,9 +109,6 @@ def render_front_matter(self, token):
since `process_doc` just converts them back to text.
"""
# TODO this data could be used to support default option values for directives
docinfo = nodes.docinfo()

try:
data = yaml.safe_load(token.content) or {}
except (yaml.parser.ParserError, yaml.scanner.ScannerError) as error:
Expand All @@ -122,15 +119,7 @@ def render_front_matter(self, token):
self.current_node += [msg_node]
return

for key, value in data.items():
if not isinstance(value, (str, int, float)):
continue
value = str(value)
field_node = nodes.field()
field_node.source = value
field_node += nodes.field_name(key, "", nodes.Text(key, key))
field_node += nodes.field_body(value, nodes.Text(value, value))
docinfo += field_node
docinfo = dict_to_docinfo(data)
self.current_node.append(docinfo)

def render_paragraph(self, token):
Expand Down Expand Up @@ -914,3 +903,22 @@ def __getattr__(self, name):
raise NotImplementedError(msg).with_traceback(sys.exc_info()[2])
msg = "{cls} has no attribute {name}".format(cls=type(self).__name__, name=name)
raise AttributeError(msg).with_traceback(sys.exc_info()[2])


def dict_to_docinfo(data):
"""Render a key/val pair as a docutils field node."""
# TODO this data could be used to support default option values for directives
docinfo = nodes.docinfo()

# Throw away all non-stringy values
# TODO: support more complex data structures as values
for key, value in data.items():
if not isinstance(value, (str, int, float)):
continue
value = str(value)
field_node = nodes.field()
field_node.source = value
field_node += nodes.field_name(key, "", nodes.Text(key, key))
field_node += nodes.field_body(value, nodes.Text(value, value))
docinfo += field_node
return docinfo

0 comments on commit e463e0a

Please sign in to comment.