我正在使用Django的标记包将restructuredText转换为html。有没有办法自定义HTML编写器以向每个<p>
标记添加类属性?
我可以为每个段落使用class directive,但我想自动执行此过程。
例如,我想要这个重组文本:
hello
=====
A paragraph of text.
转换为此HTML。
<h1>hello</h1>
<p class="specialClass">A paragraph of text.</p>
我想插入类的原因是因为我正在使用hyphenator library,它通过将连字符添加到带有“连字符”类的所有标记来工作。我可以将连字符类添加到容器标记中,但随后所有子项都将继承连字符类。我可以使用javascript动态添加类,但我认为使用restructuredText可能有一种简单的方法。
感谢您的帮助,
乔
答案 0 :(得分:5)
使用this作为参考,对内置html4css1
编写器进行子类化。
from docutils.writers import html4css1
class MyHTMLWriter(html4css1.Writer):
"""
This docutils writer will use the MyHTMLTranslator class below.
"""
def __init__(self):
html4css1.Writer.__init__(self)
self.translator_class = MyHTMLTranslator
class MyHTMLTranslator(html4css1.HTMLTranslator):
def visit_paragraph(self, node):
self.section_level += 1
self.body.append(self.starttag(node, 'p', CLASS='specialClass'))
def depart_paragraph(self, node):
self.section_level -= 1
self.body.append('</p>\n')
然后像这样使用它:
from docutils.core import publish_string
print publish_string("*This* is the input text", writer=MyHTMLWriter())
答案 1 :(得分:4)
您没有说明为什么要为每个段落添加一个类,但采用不同的方法可能更容易。例如,如果您尝试设置段落的样式,则可以使用不同的CSS技术来选择输出中的所有段落:
CSS:
div.resttext p {
/* all the styling you want... */
}
HTML:
<div class='resttext'>
<p>Blah</p>
<p>Bloo</p>
</div>
更新:既然您正在尝试使用hyphenator.js,我建议使用其selectorfunction
设置以不同方式选择元素:
Hyphenator.config({
selectorfunction: function () {
/* Use jQuery to find all the REST p tags. */
return $('div.resttext p');
}
});
Hyphenator.run();