Use Tera templates for rustdoc. by jsha · Pull Request #86157 · rust-lang/rust (original) (raw)
It's true this is mainly an initial setup to make subsequent templatizations possible, and to give a feel for what the template language will feel like. And the one format call here is the most template-like thing we currently have, since it already has named fields for interpolation. But even in this initial change you can see some of the benefits in clarity and readability. Consider:
Old:
logo = {
if layout.logo.is_empty() {
format!(
"<a href='{root}{path}index.html'>\
<div class='logo-container rust-logo'>\
<img src='{static_root_path}rust-logo{suffix}.png' alt='logo'></div></a>",
root = page.root_path,
path = ensure_trailing_slash(&layout.krate),
static_root_path = static_root_path,
suffix = page.resource_suffix
)
} else {
format!(
"<a href='{root}{path}index.html'>\
<div class='logo-container'><img src='{logo}' alt='logo'></div></a>",
root = page.root_path,
path = ensure_trailing_slash(&layout.krate),
logo = layout.logo
)
}
},
New:
<a href='{{page.root_path | safe}}{{krate_with_trailing_slash | safe}}index.html'>
<div class='logo-container'>
<img src='
{%- if layout.logo -%}
{{layout.logo}}
{%- else -%}
{{static_root_path | safe}}rust-logo{{page.resource_suffix}}.png
{%- endif -%}
' alt='logo'>
</div>
</a>
That's 20 lines vs 11 lines, and the 11 line version also removes some redundancy. Also, the HTML in the template version is easier to read without backslashes in front of all the quotes.
Performance: The difference so far will be quite negligible, because the amount of code moved in this PR is small. As we discussed in #84419, we may need to take a bit of a leap of faith performance-wise since the overall performance of templatizing everything won't be clear until we're much further along.
Byte size: struct.String.html is 54,713 bytes gzipped, vs 54,594 on master. Note that this branch doesn't have special treatment for removing excess whitespace. I used {%-
and -%}
where appropriate to take advantage of newline control, but the natural layout includes newlines and indents even between constant HTML elements, where there's no natural place for {%-
and -%}
. I think as a followup we should plan to pass the templatized content through a very basic parser that can remove HTML whitespace. If you'd like that as a prereq to landing this branch, let me know.