templ icon indicating copy to clipboard operation
templ copied to clipboard

question: Escape go keywords at the beginning of the line

Open viirak opened this issue 1 year ago • 3 comments

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?

viirak avatar Jun 02 '24 08:06 viirak

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>
}

joerdav avatar Jun 02 '24 14:06 joerdav

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:

  • Don't worry about it (as per the draft PR), because it's not actually very likely, and it's still the developer's responsibility to test.
  • Introduce extra syntax, e.g. make all Go statements start with @ or ^ (borrowed from pushup 😁 ) etc. This could be back-ported to previous code easily enough.

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?

a-h avatar Jun 04 '24 08:06 a-h

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

joerdav avatar Jun 07 '24 09:06 joerdav