a-h / templ

A language for writing HTML user interfaces in Go.
https://templ.guide/
MIT License
7.14k stars 236 forks source link

question: Escape go keywords at the beginning of the line #773

Open viirak opened 1 month ago

viirak commented 1 month ago

image

In one of my templ component I added a lot of [html] text, and the formatter eventually placed the word for at the beginning of the line, which I think templ might think it's the keyword and give me the error: expected node ...

temporary solution: I have to more those keywords away from the beginning of the line. or make it as html escape string like {`for`}

Is there a better way to handle this automatically?

joerdav commented 1 month ago

Hi, yes there is an easier way to handle this. The best way is to wrap your text in a go string literal, it can be multi-line. See more info here: https://templ.guide/syntax-and-usage/statements#ifswitchfor-within-text

And just for example:

templ t() {
    <p>{`
        My lines can
        start with go keywords
        for they are go string literals.
    `}</p>
}
a-h commented 1 month ago

I think it's is a footgun we could deal with, if we decide to relax some constraints, see draft PR.

The intention of the parser assuming that it must be code after for, if etc. is to ensure that it's really unlikely that you'd end up outputting your Server side Go code to the client instead of HTML.

For example... if you wrote in your templ:

for x := range m
  { x }
}

You'd end up writing out Go code into the HTML template, which is something we really don't want. That's the reason for the check.

I think there are at least two options:

I haven't really got a grip on the risk factor of starting a for statement, but ending up with it being malformed and outputting Go code into the HTML output. I guess there could be a heuristic warning in the generator for something that looks like it "could" be a for statement being in the strings.

Thoughts?

joerdav commented 4 weeks ago

I'm for the "don't worry about it option". I'm just thinking if there are any mitigations we can think of that could help this?

One mitigation is that when templ formats your code it will probably be clear that it did not parse it as a for