Best way of returning HTML, CSS and JS?

Hi,
I need a server side rendering endpoint.

I have the complete HTML with inline CSS and inline JS in a template.

This is very clumsy and I had already to split the escape syntax to enable the backtick. But it works well! :ok_hand:

I tried to split this into 3 different templates and combine it. But it fails:
Sometimes it looks great but then the JS is not running in the browser.

I am sure I could handle it somehow with more effort, but maybe someone does it all the time and has found a very simple way? :slight_smile:

The question is:
How do you manage your complex templates in GO that you need to server side render?
I want the JS to be as “natural” as possible, because I need to develop it as well.
I want the result to be one inline html file.

AI struggles hard with this for longer files.
It seems to get confused by the syntax and is unable to handle it correctly :robot: :exploding_head:

	data := TemplateData{
		BaseURL:      baseUrl,
		SessionToken: sessionToken,
		Id:           idParam,
	}

	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	if err := tmpl.Execute(w, data); err != nil {
		http.Error(w, "Failed to render page", http.StatusInternalServerError)
		return
	}

}

// Data structure for the template
type TemplateData struct {
	BaseURL      string
	SessionToken string
	Id           string
}

// Global template variable
var tmpl = template.Must(template.New("index").Parse(`<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Custom LLM Persona - Anam Integration</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
            background-color: #f5f5f5;
        }
// This is one issue. Escaping Syntax.
formData.append("audio", audioBlob, ` + "`audio_${Date.now()}.ogg`" + `);

I found this. Worth using? :slight_smile:

I haven’t used templ but I know it is well regarded. I just reviewed the documentation and it LOOKS pretty great!

I would definitely use embedded file system for large string constants. Put a file called template.html in your source-code. Put all your template code in there (no escaping needed) and then use

//go:embed template.html
var tmplStr string

This will include the content of the html-file at build time so you will still only have a single exe file as output and the string contents in the variable, as if you would have written it as a string literal.

Upsides are better formatting, cleaner separation of code, syntax highlighting while editing the template and no problems with escaping.

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.