Skip to content

Commit

Permalink
feat: warn about invalid templ comment syntax, add docs
Browse files Browse the repository at this point in the history
  • Loading branch information
a-h committed Sep 29, 2023
1 parent 08e1416 commit 5482874
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 5 deletions.
40 changes: 40 additions & 0 deletions docs/docs/03-syntax-and-usage/11-comments.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# Comments

# HTML comments

Inside templ statements, use HTML comments.

```templ title="template.templ"
templ template() {
<!-- Single line -->
<!--
Single or multiline.
-->
}
```

Comments are rendered to the template output.

```html title="Output"
<!-- Single line -->
<!--
Single or multiline.
-->
```

As per HTML, nested comments are not supported.

# Go comments

Outside of templ statements, use Go comments.

```templ
package main
// Use standard Go comments outside templ statements.
var greeting = "Hello!"
templ hello(name string) {
<p>{greeting} { name }</p>
}
```
11 changes: 7 additions & 4 deletions parser/v2/commentparser.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
package parser

import (
"fmt"

"github.com/a-h/parse"
)

var htmlCommentStart = parse.String("<!--")
var htmlCommentEnd = parse.String("-->")
var htmlCommentEnd = parse.String("--")

type commentParser struct {
}
Expand All @@ -22,11 +20,16 @@ func (p commentParser) Parse(pi *parse.Input) (c Comment, ok bool, err error) {

// Once we've got the comment start sequence, parse anything until the end
// sequence as the comment contents.
if c.Contents, ok, err = Must(parse.StringUntil(htmlCommentEnd), fmt.Sprintf("expected end comment sequence not present")).Parse(pi); err != nil || !ok {
if c.Contents, ok, err = Must(parse.StringUntil(htmlCommentEnd), "expected end comment literal '-->' not found").Parse(pi); err != nil || !ok {
return
}
// Cut the end element.
_, _, _ = htmlCommentEnd.Parse(pi)

// Cut the gt.
if _, ok, err = Must(gt, "comment contains invalid sequence '--'").Parse(pi); err != nil || !ok {
return
}

return c, true, nil
}
11 changes: 10 additions & 1 deletion parser/v2/commentparser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,13 +73,22 @@ func TestCommentParserErrors(t *testing.T) {
{
name: "unclosed HTML comment",
input: `<!-- unclosed HTML comment`,
expected: parse.Error("expected end comment sequence not present",
expected: parse.Error("expected end comment literal '-->' not found",
parse.Position{
Index: 26,
Line: 0,
Col: 26,
}),
},
{
name: "comment in comment",
input: `<!-- <-- other --> -->`,
expected: parse.Error("comment contains invalid sequence '--'", parse.Position{
Index: 8,
Line: 0,
Col: 8,
}),
},
}
for _, tt := range tests {
tt := tt
Expand Down

0 comments on commit 5482874

Please sign in to comment.