是否有一种在reStructuredText中合成标准文本角色的方法?例如,将字符串格式化为文字和强字符串?
以下不是我所希望的:
**``text``**
``**text**``
:strong:`:literal:`text``
:literal:`:strong:`text``发布于 2017-06-29 17:41:36
不,这是不可能的。传递给实现角色的函数(参数text)的内容不再被进一步解析。
见创建reStructuredText解释的文本角色。
也就是说,您可以实现自己的rst角色,如果您愿意的话,它可以通过nested_parse()进一步解析文本--但这不是您想要的。
附加细节
来自docutils/docutils/parsers/rst/roles.py的评论表明,您正在询问的嵌套解析特性是计划的/是计划的/建议的,但到目前为止还没有实现。
# Once nested inline markup is implemented, this and other methods should
# recursively call inliner.nested_parse().发布于 2021-08-20 17:00:19
(以下内容在CC0下发布。)
如果您有能力扩展解析器(例如,如果使用Sphinx),则可以添加解析其内容的自定义角色。(请注意,这对于粗体/斜体和替换之类的简单事物是有效的,但是如果你试图嵌套角色或类似的疯狂,它很可能会掉到它的脸上。
我用这个:
from docutils import nodes
from docutils.parsers.rst.states import Struct
def make_parsed_text_role(class_names=[], node_class=nodes.inline):
def parsed_text_role(name, rawtext, text, lineno, inliner,
options={}, content=[]):
# Prepare context for nested parsing
memo = Struct(document=inliner.document,
reporter=inliner.reporter,
language=inliner.language)
# Create parent node
options['classes'] = class_names
parent = node_class(rawtext, '', **options)
# Parse role text for markup and add to parent
processed, messages = inliner.parse(text, lineno, memo, parent)
parent += processed
# Return parent node, and any messages from nested parsing
return [parent], messages
return parsed_text_role您可以通过狮身人面像conf.py使用它,如下所示:
# Configuration file for the Sphinx documentation builder (conf.py).
project = 'My Documentation'
# ...
# ...paste the above code here...
def setup(app):
app.add_role('foo', make_parsed_text_role(class_names=['foo']))在您的文档中,这将允许您编写:
This is :foo:`some **bold** text`!在HTML中,这将产生一个<span class="foo">,至少对于默认的nodes.inline节点类是这样。生成器模式的使用是可选的,但如果您想要生成大量这些自定义角色,则非常方便。
https://stackoverflow.com/questions/44829580
复制相似问题