Skip to content
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

spaceless feature from Django #641

Closed
jsha opened this issue Jun 21, 2021 · 3 comments · Fixed by #643
Closed

spaceless feature from Django #641

jsha opened this issue Jun 21, 2021 · 3 comments · Fixed by #643

Comments

@jsha
Copy link
Contributor

jsha commented Jun 21, 2021

For rustdoc, we're adopting tera templates. We try to generate HTML with as little unneeded whitespace as necessary, to keep page sizes small. Currently we're doing that manually; with tera templates we'll be using {%- -%}. But we still have to deal with newlines and indenting whitespace that we use purely to make the templates more readable.

Per the linked issue, we'll be adding an empty comment to the end of each line, with the whitespace control characters: {#- -#}. That does the job, but it's somewhat tedious and hurts readability.

Evidently Django has a spaceless directive that is HTML tag aware and knows how to strip all whitespace between tags. If we could use that with tera templates it could considerably improve the readability and writeability of our templates.

There's a similar issue for attributes within a tag, and I don't know if other place in the jinja ecosystem have a good solution. Specifically, given a template like:

<link rel="stylesheet" type="text/css"
      href="{{static_root_path | safe}}normalize{{page.resource_suffix}}.css">

We'd like that to render with exactly one space character between css" and href=. The end-of-line-comment trick doesn't work because it would concatenate the attributes. We can use a {{- " " -}}, but it would be great if there were something similar to spaceless for this case.

@Keats
Copy link
Owner

Keats commented Jun 21, 2021

That means Tera need to parse HTML. I would take a PR for it if whatever dependency it requires is not enabled by default.

@Urgau
Copy link
Contributor

Urgau commented Jun 21, 2021

Just by curiosity I looked at what Django does, and it's really "stupid":

def strip_spaces_between_tags(value):
    """Return the given HTML with spaces between tags removed."""
    return re.sub(r'>\s+<', '><', str(value))

It's just a regex that's do a substitution.

@Keats
Copy link
Owner

Keats commented Jun 21, 2021

Oh i'm surprised that works but then it would be easy to make that a filter in Tera

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants