Skip to content

templ fmt corrupts script tags with data-templ-depth divs when prettier is in PATH #1277

@ashmortar

Description

@ashmortar

Bug Description

When templ fmt is run on a file containing script tags and prettier is available in the PATH, the formatter corrupts the script tags by adding data-templ-depth divs that are not properly removed, resulting in invalid HTML.

Environment

  • templ version: v0.3.943
  • prettier in PATH: yes
  • OS: Linux

Reproduction Steps

  1. Create a simple templ file with a script tag:
package test

templ TestScriptSimple() {
	<div>
		<h1>Test Page</h1>
		<script>
			console.log("Hello, World!");
			function test() {
				return "test";
			}
		</script>
	</div>
}
  1. Run templ fmt on the file

  2. The script tag becomes corrupted:

<script><div data-templ-depth="0"><div data-templ-depth="1"><script>
	console.log("Hello, World!");
	function test() {
		return "test";
	}
</script></div></div></script>

Expected Behavior

The script tag should remain unchanged or be properly formatted without corruption.

Actual Behavior

The formatter adds:

  • Two nested <div data-templ-depth="N"> tags inside the script
  • An extra opening <script> tag
  • Extra closing tags </div></div></script>

This creates invalid HTML where divs are placed inside script tags, which breaks JavaScript execution.

Root Cause Analysis

Based on examining the prettier.go source code, the issue appears to be in the prettier integration added in v0.3.920. The Element() function in internal/prettier/prettier.go:

  1. Intentionally adds data-templ-depth div wrappers to help prettier understand indentation
  2. Should remove these divs after prettier formats the content
  3. The removal mechanism fails, leaving the temporary divs in the source file

Impact

This bug corrupts any templ file with script tags when formatted, making the HTML invalid and breaking JavaScript functionality.

Workaround

Currently, the only workaround is to either:

  1. Remove prettier from PATH before running templ fmt
  2. Avoid using templ fmt on files with script tags
  3. Manually fix the corruption after formatting

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions