【问题标题】:How to get restructuredText to add a class to every html <p> tag?如何让 restructuredText 为每个 html <p> 标签添加一个类?
【发布时间】:2010-12-22 16:17:59
【问题描述】:

我正在使用 Django 的标记包将 restructuredText 转换为 html。有没有办法自定义 HTML 编写器为每个 &lt;p&gt; 标签添加一个类属性?

我可以为每个段落使用class directive,但我想自动化这个过程。

例如,我想要这个重组后的文本:

hello
=====

A paragraph of text.

要转换成这个html。

<h1>hello</h1>
<p class="specialClass">A paragraph of text.</p>

我想插入类的原因是因为我使用的是hyphenator library,它通过向所有带有“连字符”类的标签添加连字符来工作。我可以将连字符类添加到容器标签中,但是所有的孩子都会继承连字符类。我可以使用 javascript 来动态添加类,但我认为使用 restructuredText 可能有一种简单的方法。

感谢您的帮助,

【问题讨论】:

    标签: python django restructuredtext


    【解决方案1】:

    子类化内置的html4css1 writer,使用this作为参考..

    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())
    

    【讨论】:

      【解决方案2】:

      您没有说明为什么要为每个段落添加一个类,但采用不同的方法可能更容易。例如,如果您尝试设置段落样式,则可以使用不同的 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();
      

      【讨论】:

      • +1 使用 CSS 来设置样式(不依赖于类的插入)是最合理的方法。
      • 我在我的问题中添加了一些说明。我需要一个 javascript 库的类。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-01
      • 1970-01-01
      相关资源
      最近更新 更多