diff --git a/docs/docs/03-syntax-and-usage/11-comments.md b/docs/docs/03-syntax-and-usage/11-comments.md new file mode 100644 index 000000000..f98bb0b01 --- /dev/null +++ b/docs/docs/03-syntax-and-usage/11-comments.md @@ -0,0 +1,40 @@ +# Comments + +# HTML comments + +Inside templ statements, use HTML comments. + +```templ title="template.templ" +templ template() { + + +} +``` + +Comments are rendered to the template output. + +```html title="Output" + + +``` + +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) { +
{greeting} { name }
+} +``` diff --git a/parser/v2/commentparser.go b/parser/v2/commentparser.go index a012a052d..be05ce09e 100644 --- a/parser/v2/commentparser.go +++ b/parser/v2/commentparser.go @@ -1,13 +1,11 @@ package parser import ( - "fmt" - "github.com/a-h/parse" ) var htmlCommentStart = parse.String("") +var htmlCommentEnd = parse.String("--") type commentParser struct { } @@ -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 } diff --git a/parser/v2/commentparser_test.go b/parser/v2/commentparser_test.go index 5ed8fa845..0a0e08f90 100644 --- a/parser/v2/commentparser_test.go +++ b/parser/v2/commentparser_test.go @@ -73,13 +73,22 @@ func TestCommentParserErrors(t *testing.T) { { name: "unclosed HTML comment", input: `' not found", parse.Position{ Index: 26, Line: 0, Col: 26, }), }, + { + name: "comment in comment", + input: ` -->`, + expected: parse.Error("comment contains invalid sequence '--'", parse.Position{ + Index: 8, + Line: 0, + Col: 8, + }), + }, } for _, tt := range tests { tt := tt