Skip to content

Implement and document the raw option #4

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions docs/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,22 @@ To see the rendered templates in the built documentation, use the ``debug`` opti

Hallo **{{ name }}**!



Raw output
**********

The role can be used to produce raw ouput instead of interpreted RST:

.. jinja2-example::

.. jinja::
:ctx: {"name": "World"}
:raw: html

Hello <em>{{ name }}</em>


Warning messages
****************

Expand Down
21 changes: 15 additions & 6 deletions src/sphinx_jinja2/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,8 @@ class JinjaOptions(TypedDict, total=False):
relative to current file, or src directory (if starts with ``/``) """
debug: bool
"""Also output the rendered template"""
raw: str
"""The rendered template is raw output in given format, rather than input put back into the source parser."""


class JinjaDirective(SphinxDirective):
Expand All @@ -97,6 +99,7 @@ class JinjaDirective(SphinxDirective):
"file": directives.path,
"ctx": directives.unchanged,
"debug": directives.flag,
"raw": directives.unchanged,
}
options: JinjaOptions
arguments: list[str]
Expand Down Expand Up @@ -187,12 +190,18 @@ def _warn(msg: str) -> None:
_warn(f"Error rendering jinja template: {exc.__class__.__name__}: {exc}")
return []

# insert the new content into the source stream
# setting the source and line number
new_lines = StringList(
new_content.splitlines(), items=[(source, line - 1) for _ in new_content.splitlines()]
)
self.state_machine.insert_input(new_lines, source)
if "raw" not in self.options:
# insert the new content into the source stream
# setting the source and line number
new_lines = StringList(
new_content.splitlines(),
items=[(source, line - 1) for _ in new_content.splitlines()],
)
self.state_machine.insert_input(new_lines, source)
else:
raw_node = nodes.raw("", new_content, classes=[], format=self.options["raw"])
(raw_node.source, raw_node.line) = self.state_machine.get_source_and_line(self.lineno)
return [raw_node]

if conf.debug or "debug" in self.options:
# return the rendered template
Expand Down