templ icon indicating copy to clipboard operation
templ copied to clipboard

Can i use templ to generate text instead of html ?

Open ymolists opened this issue 1 year ago • 3 comments

Hi folks

I am wondering if it is possible to replace all my go template based code with templ. I am hoping that this is already supported. I imagine that this could be a usecase many people would want. As in we have the equivalent of html/text templates in the go standard library.

Regards

ymolists avatar Jan 02 '24 13:01 ymolists

Why would you use it in that way?

fontseca avatar Jan 02 '24 20:01 fontseca

Hi @ymolists - sorry to disappoint, but there's no plan to support the generation of plain text (or YAML, or anything else) with templ templates. The vision of templ is purely to...

Enable Go developers to build strongly typed, component-based HTML user interfaces with first-class developer tooling, and a short learning curve.

But... if you wanted to abuse templ to do it, you could, by stripping the HTML tags and getting the plain text. Obviously, there are various risks with this, and the performance isn't going to be as good, since you're parsing the HTML. However, it still might be faster than the built in Go templates.

With this template:

package main

templ Header() {
	<div>This is a header</div>
}

templ Footer() {
	<div>This is a footer</div>
}

templ TextTemplate(content string) {
	@Header()
	<p>
		{ content }
	</p>
	@Footer()
}

And this code...

package main

import (
	"context"
	"fmt"
	"log"
	"strings"

	"github.com/k3a/html2text"
)

func main() {
	ctx := context.Background()
	w := new(strings.Builder)
	err := TextTemplate("Put this & this text into your template").Render(ctx, w)
	if err != nil {
		log.Fatalf("failed to render: %v", err)
	}
	s := html2text.HTML2Text(w.String())
	fmt.Println(s)
}

You get the output:

This is a header

Put this & this text into your template

This is a footer

I'm not willing to support this sort of thing, since it's a bit of a niche use case, but it's possible.

a-h avatar Jan 02 '24 21:01 a-h

Why would you use it in that way?

The point is there are amny tools that only generate text. tmpl provides a way that is type safe and that also has lsp support. Right now everyone is forced to use go templates which is a really bad option for all sorts of reasons the mnimum being not being type safe and cumbersome. I hope i dont have to convince any that that go templating is terrible !

temple seems like a really nice template framework that could be the de facto text/code generation instead of go template because its based on generated code. The hardest part here i guess is the lsp integration.

ymolists avatar Jan 02 '24 22:01 ymolists

I'm going to close this, since I think the question is answered, and it's not an issue with templ.

a-h avatar Jan 05 '24 22:01 a-h