text/template or strings.Replace?

1,863 views
Skip to first unread message

Jordan Wright

unread,
Mar 9, 2016, 7:22:57 PM3/9/16
to golang-nuts
Hey everyone,

I have a use case where I'm allowing users to create templates that can have certain variables (e.g. {{.FirstName}}). Think of it like a mailing application.

I'm currently using text/template. The problem I'm running into is that many users mistakenly use incorrect template variables (missing a ".", or using something that isn't in their data model passed to the template, etc.). These users are *not* Go devs. Their' just normal users, so they don't know the in's and outs of templating.

From what I've read, there doesn't appear to be much in the way of error handling with templates. For example, if the user forgets a ".", the app crashes. The same goes for if the user tries to use a value that isn't there.

Since this simple find/replacing is the only thing I'm using templates for, would it be safer just to use strings.Replace, or would that be unidiomatic?

Any help is greatly appreciated!

Jordan

Matt Silverlock

unread,
Mar 9, 2016, 8:44:59 PM3/9/16
to golang-nuts
Packer's template package might help simplify: https://github.com/mitchellh/packer/tree/master/template

Matt Silverlock

unread,
Mar 9, 2016, 8:45:22 PM3/9/16
to golang-nuts

Matt Harden

unread,
Mar 9, 2016, 10:06:48 PM3/9/16
to Matt Silverlock, golang-nuts
I haven't seen templates crash the program. Are you using the template.Must function by chance? That's intended to only be used when you know the template is valid; it intentionally panics if any error occurs. Otherwise you should check the error from template.Parse*.

On Wed, Mar 9, 2016 at 5:45 PM Matt Silverlock <elit...@gmail.com> wrote:
--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Aliaksandr Valialkin

unread,
Mar 10, 2016, 6:06:14 PM3/10/16
to golang-nuts
Try https://github.com/valyala/fasttemplate . It looks like it perfectly fits your needs:
- it provides simple 'replace placeholders with values' functionality .
- it works faster than strings.Replace .
Reply all
Reply to author
Forward
0 new messages