From d960f2265d7a035459f0b0200c26d07dd999c4b5 Mon Sep 17 00:00:00 2001 From: Takeshi KOMIYA Date: Thu, 2 May 2019 13:46:22 +0900 Subject: [PATCH] Add ReSTRenderer --- sphinx/util/template.py | 16 +++++++++++++++- tests/test_util_template.py | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 1 deletion(-) create mode 100644 tests/test_util_template.py diff --git a/sphinx/util/template.py b/sphinx/util/template.py index c33e16819..b521c5c79 100644 --- a/sphinx/util/template.py +++ b/sphinx/util/template.py @@ -15,7 +15,7 @@ from jinja2.sandbox import SandboxedEnvironment from sphinx import package_dir from sphinx.jinja2glue import SphinxFileSystemLoader from sphinx.locale import get_translator -from sphinx.util import texescape +from sphinx.util import rst, texescape if False: # For type annotation @@ -84,3 +84,17 @@ class LaTeXRenderer(SphinxRenderer): self.env.variable_end_string = '%>' self.env.block_start_string = '<%' self.env.block_end_string = '%>' + + +class ReSTRenderer(SphinxRenderer): + def __init__(self, template_path=None, language=None): + # type: (str, str) -> None + super().__init__(template_path) + + # add language to environment + self.env.extend(language=language) + + # use texescape as escape filter + self.env.filters['e'] = rst.escape + self.env.filters['escape'] = rst.escape + self.env.filters['heading'] = rst.heading diff --git a/tests/test_util_template.py b/tests/test_util_template.py new file mode 100644 index 000000000..b25e9dc87 --- /dev/null +++ b/tests/test_util_template.py @@ -0,0 +1,37 @@ +""" + test_util_template + ~~~~~~~~~~~~~~~~~~ + + Tests sphinx.util.template functions. + + :copyright: Copyright 2007-2019 by the Sphinx team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +from sphinx.util.template import ReSTRenderer + + +def test_ReSTRenderer_escape(): + r = ReSTRenderer() + template = '{{ "*hello*" | e }}' + assert r.render_string(template, {}) == r'\*hello\*' + + +def test_ReSTRenderer_heading(): + r = ReSTRenderer() + + template = '{{ "hello" | heading }}' + assert r.render_string(template, {}) == 'hello\n=====' + + template = '{{ "hello" | heading(1) }}' + assert r.render_string(template, {}) == 'hello\n=====' + + template = '{{ "русский язык" | heading(2) }}' + assert r.render_string(template, {}) == ('русский язык\n' + '------------') + + # language: ja + r.env.language = 'ja' + template = '{{ "русский язык" | heading }}' + assert r.render_string(template, {}) == ('русский язык\n' + '=======================')