templ
templ copied to clipboard
templ fmt does not indent style tag properly
Say I have the following code
After running templ fmt . it will look like this.
So the divs and such are are indented correctly, but the closing style tag with content is not.
Please let me know if more info is needed.
templ info output
Happy to take this on.
So I've been trying to get a little more familiar with this issue. I've mainly been focusing my efforts in generator.go around indent levels. From the code example provided, it looks like the style tag is not indenting child nodes as we expect, and its closing tag.
Knowing that, I think the issue is inside either writeTemplBuffer, writeTemplate, or writeNode.
I will keep poking around for now but could probably use some confirmation I'm at least looking in the right area.
And just so we're on the same page, this is what the expected result should be, right?
templ leftRight(left templ.Component, right templ.Component) {
<style>
body {
background: black;
}
</style>
<div class="flex flex-col items-center justify-center h-screen">
<div></div>
<div class="flex flex-row">
@left
@right
</div>
<div>
Se priser
</div>
</div>
}
I think this does the same thing with <script> tags - mainly the closing </script> tags.
So, you've probably figured out that templ fmt formats templ files by parsing a template file into an object model, then writing it back out again.
You can see that in action here: https://github.com/a-h/templ/blob/850120161a0434ee73b92810f02e4def8a70c850/cmd/templ/fmtcmd/main.go#L141-L166
Note that the TemplateFile.Write method writes the object model out: https://github.com/a-h/templ/blob/850120161a0434ee73b92810f02e4def8a70c850/parser/v2/types.go#L128-L150
So you can see that each Node gets written out in turn.
The script and style elements are parsed into the following types: https://github.com/a-h/templ/blob/850120161a0434ee73b92810f02e4def8a70c850/parser/v2/types.go#L669-L703
By this parsing code: https://github.com/a-h/templ/blob/850120161a0434ee73b92810f02e4def8a70c850/parser/v2/raw.go
I can see that the style and script tags don't populate out a TrailingSpace, like the other elements do: https://github.com/a-h/templ/blob/850120161a0434ee73b92810f02e4def8a70c850/parser/v2/elementparser.go#L496
I think ths issue is probably:
- Not parsing trailing whitespace into the object model, so it can't be retained properly.
- Not writing out appropriate indentation in the
Writemethod to ensure that the</script>/</style>element is properly indented.
Note that there's some formatting tests alonside the templ fmt command, so that's a good place to add test cases.
Hope that helps you track it down!
This is solved by https://github.com/a-h/templ/pull/1230
Fix merged in https://github.com/a-h/templ/pull/1230 - uses prettier to format CSS where available.