Skip to content

Commit 2aa47c8

Browse files
authored
html: Support passing custom_template as string. (#118)
Will be used in DVCLive for treeverse/dvclive#460
1 parent d0023df commit 2aa47c8

File tree

2 files changed

+26
-10
lines changed

2 files changed

+26
-10
lines changed

src/dvc_render/html.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -79,17 +79,18 @@ def embed(self) -> str:
7979
def render_html(
8080
renderers: List["Renderer"],
8181
output_file: "StrPath",
82-
template_path: Optional["StrPath"] = None,
82+
html_template: Optional["StrPath"] = None,
8383
refresh_seconds: Optional[int] = None,
8484
) -> "StrPath":
85-
"User renderers to fill an HTML template and write to path."
85+
"Use `renderers` to fill an HTML template and write to `output_file`."
8686
output_path = Path(output_file)
8787
output_path.parent.mkdir(exist_ok=True)
8888

89-
page_html = None
90-
if template_path:
91-
with open(template_path, encoding="utf-8") as fobj:
92-
page_html = fobj.read()
89+
page_html: Optional[str] = None
90+
if html_template and Path(html_template).is_file():
91+
page_html = Path(html_template).read_text(encoding="utf8")
92+
elif isinstance(html_template, str):
93+
page_html = html_template
9394

9495
document = HTML(page_html, refresh_seconds=refresh_seconds)
9596

tests/test_html.py

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,7 @@
1-
import pytest
2-
3-
from dvc_render.html import HTML, PAGE_HTML, MissingPlaceholderError
4-
51
# pylint: disable=missing-function-docstring, R0801
2+
import pytest
63

4+
from dvc_render.html import HTML, PAGE_HTML, MissingPlaceholderError, render_html
75

86
CUSTOM_PAGE_HTML = """<!DOCTYPE html>
97
<html>
@@ -68,6 +66,23 @@ def test_html(template, page_elements, expected_page):
6866
assert result == expected_page
6967

7068

69+
def test_render_html_with_custom_template(mocker, tmp_dir):
70+
output_file = tmp_dir / "output_file"
71+
72+
render_html(mocker.MagicMock(), output_file)
73+
assert output_file.read_text() == PAGE_HTML.replace("{plot_divs}", "").replace(
74+
"{scripts}", ""
75+
).replace("{refresh_tag}", "")
76+
77+
render_html(mocker.MagicMock(), output_file, CUSTOM_PAGE_HTML)
78+
assert output_file.read_text() == CUSTOM_PAGE_HTML.format(plot_divs="")
79+
80+
custom_template = tmp_dir / "custom_template"
81+
custom_template.write_text(CUSTOM_PAGE_HTML)
82+
render_html(mocker.MagicMock(), output_file, custom_template)
83+
assert output_file.read_text() == CUSTOM_PAGE_HTML.format(plot_divs="")
84+
85+
7186
def test_no_placeholder():
7287
template = "<head></head><body></body>"
7388

0 commit comments

Comments
 (0)