Lindenii Project Forge
Login

go-htmpl

Simple HTML templating engine
Commit info
ID
3d96597ec1f543a6ab04ab9ad0bfe695f4ab133b
Author
Runxi Yu <me@runxiyu.org>
Author date
Wed, 19 Mar 2025 12:48:41 +0800
Committer
Runxi Yu <me@runxiyu.org>
Committer date
Wed, 19 Mar 2025 12:48:41 +0800
Actions
Further renaming
*.o
/parse.c
/parse.h
/htmplgen
/gohtmplgen
CC = cc
YACC = yacc
CFLAGS = -Wall -Werror -O2
YFLAGS = -d
LDFLAGS =

TARGET = htmplgen
TARGET = gohtmplgen

PREFIX ?= /usr/local

SRCS = htmplgen.c parse.y
OBJS = htmplgen.o parse.o
SRCS = gohtmplgen.c parse.y
OBJS = gohtmplgen.o parse.o

all: $(TARGET)

parse.c parse.h: parse.y
	$(YACC) $(YFLAGS) -o parse.c $<

htmplgen.o: htmplgen.c parse.h
gohtmplgen.o: gohtmplgen.c parse.h
	$(CC) $(CFLAGS) -c -o $@ $<

parse.o: parse.c
	$(CC) $(CFLAGS) -c -o $@ $<

$(TARGET): $(OBJS)
	$(CC) $(LDFLAGS) -o $@ $(OBJS)

clean:
	rm -f $(TARGET) $(OBJS) parse.c parse.h *~

install: $(TARGET)
	install -d $(DESTDIR)$(PREFIX)/bin
	install -m 755 $(TARGET) $(DESTDIR)$(PREFIX)/bin/

.PHONY: all clean install
# go-htmpl – A simple HTML templating engine

This is a Go port of the HTML templating engine used in
[Got](https://got.gameoftrees.org/?action=summary&path=got.git)
and described in
[Omar Polo's blog post](https://www.omarpolo.com/post/template.html).

The `gohtmplgen` program generates a Go file from the template file.
The `gogohtmplgen` program generates a Go file from the template file.

Each template is presented as a function that accepts an
`net/http.ResponseWriter` and other user-defined parameters, if any.

## Dependencies

- [Go](https://go.dev)
- A POSIX-compatible Yacc implementation, such as
  [Bison](https://www.gnu.org/software/bison/)
- A C compiler

## License

This inherits the ISC license from the original code. See the LICENSE file.

## Contributing

Create a branch that begins with `contrib/` and push to the
[main repo](https://forge.lindenii.runxiyu.org/hare/:/repos/go-htmpl/)
via SSH directly.

```
git clone ssh://forge.lindenii.runxiyu.org/hare/:/repos/go-htmpl/
cd go-htmpl
git checkout -b contrib/whatever
# edit and commit stuff
git push -u origin HEAD
```

## Support

[`#chat`](https://webirc.runxiyu.org/kiwiirc/#chat)
on
[irc.runxiyu.org](https://irc.runxiyu.org/).
.\" Copyright (c) 2022 Omar Polo <op@openbsd.org>
.\"
.\" Permission to use, copy, modify, and distribute this software for any
.\" purpose with or without fee is hereby granted, provided that the above
.\" copyright notice and this permission notice appear in all copies.
.\"
.\" THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
.\" WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
.\" MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
.\" ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
.\" WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
.\" ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
.\" OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
.\"
.Dd January 6, 2022
.Dt TEMPLATE 7
.Os
.Sh NAME
.Nm htmpl
.Nd templating language
.Sh DESCRIPTION
.Nm
is a language used to define programs that output HTML.
These programs are called
.Dq templates .
A
.Nm
file is assumed to be compiled using the
.Xr htmplgen 1
utility into Hare code, to be further compiled as part of a bigger
.Xr gohtmplgen 1
utility into Go code, to be further compiled as part of a bigger
application.
.Pp
There are two special sequences:
.Bl -tag -width 9m
.It Cm {{ Ar ... Cm }}
used for
.Nm
special syntax.
.It Cm {! Ar ... Cm !}
used to include literal Hare code.
used to include literal Go code.
This is the only special syntax permitted as top-level, except for block
definition and includes.
.El
.Pp
The basic unit of a
.Nm
file is the block.
Each block is turned into a Hare function that output its content via some
Each block is turned into a Go function that output its content via some
provided functions. The block must accept an argument called
.Ar handle
that satisfies io::handle.
.Pp
Here's an example of a block:
.Bd -literal -offset indent
{{ define tp_base(handle: io::handle, title: str) (void | io::error | nomem) }}
<!doctype html>
<html>
	<head>
		<title>{{ title }}</title>
	</head>
	<body>
		{{ render tp_body(tp) }}
	</body>
</html>
{{ end }}
.Ed
.Ss SPECIAL SYNTAX
This section is a reference for all the special syntaxes supported.
.Bl -tag -width Ds
.It Cm {{ Ic include Ar file Cm }}
Include additional template files.
.It Cm {{ Ic define Ar name Ns ( Ar arguments ... ) Cm }} Ar body Cm {{ Ic end Cm }}
Defines the block
.Ar name
with the given
.Ar arguments .
.Ar body
will be outputted as-is via the provided functions
.Pq i.e.\& is still escaped eventually
and can contain all the special syntaxes documented here except
.Ic include
and
.Ic define .
.It Cm {{ Ic render Ar expression() Cm }}
Executes
.Ar expression()
and terminate the template if it returns an error.
It's used to render (call) another template.
.It Cm {{ Ic printf Ar fmt , Ar arguments ... Cm }}
Outputs the string that would be produced by calling
.Xr printf 3
with the given
.Ar fmt
format string and the given
.Ar arguments .
.It Cm {{ Ic if Ar expr Cm }} Ar ... Cm {{ Ic elseif Ar expr Cm }} Ar ... Cm {{ Ic else Cm }} Ar ... Cm {{ Ic end Cm }}
Conditional evaluation.
.Ic elseif
can be provided zero or more times,
.Ic else
only zero or one time and always for last.
.It Cm {{ Ic for Ar ... ; Ar ... ; Ar ... Cm }} Ar ... Cm {{ Ic end Cm }}
Looping construct similar to the Hare for loop.
Looping construct similar to the Go for loop.
.It Cm {{ Ic while Ar ... Cm }} Ar ... Cm {{ Ic end Cm }}
Looping construct similar to the Hare for loop with one condition argument only.
Looping construct similar to the Go for loop with one condition argument only.
.It Cm {{ Ar expression Cm \&| Ic unsafe Cm }}
Output
.Ar expression
as-is.
.It Cm {{ Ar expression Cm \&| Ic urlescape Cm }}
Output
.Ar expression
escaped in a way that can be made part of an URL.
.It Cm {{ Ar expression Cm }}
Output
.Ar expression
with the default HTML escaping.
.El
.Sh SEE ALSO
.Xr htmplgen 1
.Xr gohtmplgen 1
.Sh AUTHORS
.An Omar Polo Aq Mt op@openbsd.org
wrote the original program.
.An Runxi Yu Aq Mt op@openbsd.org
ported it to Hare.
ported it to Go.
.\" Copyright (c) 2022 Omar Polo <op@openbsd.org>
.\"
.\" Permission to use, copy, modify, and distribute this software for any
.\" purpose with or without fee is hereby granted, provided that the above
.\" copyright notice and this permission notice appear in all copies.
.\"
.\" THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
.\" WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
.\" MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
.\" ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
.\" WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
.\" ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
.\" OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
.\"
.Dd January 6, 2022
.Dt TEMPLATE 1
.Os
.Sh NAME
.Nm htmplgen
.Nm gohtmplgen
.Nd templating system compiler
.Sh SYNOPSIS
.Nm
.Op Fl G
.Op Fl o Ar out
.Op Ar
.Sh DESCRIPTION
.Nm
is an utility that converts files written in the
.Xr htmpl 7
format format to a set of routine writtens in the C programming
language.
.Nm
converts the files given as arguments or from standard input, and
writes to standard output.
.Pp
The options are as follows:
.Bl -tag -width Ds
.It Fl G
Do not emit debug info in the generated source.
.It Fl o Ar out
Write output to file.
.Ar out
will be created or truncated if exists and will be removed if
.Nm
encounters any error.
.El
.Sh EXIT STATUS
.Ex -std
.Sh SEE ALSO
.Xr htmpl 7
.Sh AUTHORS
.An -nosplit
.An Omar Polo Aq Mt op@openbsd.org
wrote the original version in C.
.An Runxi Yu Aq Mt me@runxiyu.org
ported it to Hare.
.Sh CAVEATS
The compiler is very naive, so there are quite a few shortcomings:
.Bl -bullet -compact
.It
No attempt is made to validate the Hare code provided inline, nor the
validity of the arguments to many constructs.
.It
The generated code assumes that a variable called
.Va handle
of type
.Vt io::handle
is in scope inside each block.
.It
Each block may have additional variables used for the template
generation implicitly defined: to avoid clashes, don't name variables
or arguments with the
.Sq _htmpl_
prefix.
.It
Blanks are, in most cases, trimmed.
Normally this is not a problem, but a workaround is needed in case
they need to be preserved, for e.g.:
.Bd -literal -offset indent
Name: {{ " " }} {{ render name_field(tp) }}
.Ed
.El
/*
 * Copyright (c) 2025 Runxi Yu <https://runxiyu.org>
 * Copyright (c) 2022 Omar Polo <op@openbsd.org>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <err.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int parse(FILE *, const char *);

int nodebug;

void
usage(char *progname)
{
	fprintf(stderr, "usage: %s [-G] [-o out] [file ...]\n", progname);
	exit(1);
}

int
main(int argc, char **argv)
{
	FILE *fp = stdout;
	const char *out = NULL;
	int ch, i;

	while ((ch = getopt(argc, argv, "Go:")) != -1) {
		switch (ch) {
		case 'G':
			nodebug = 1;
			break;
		case 'o':
			out = optarg;
			break;
		default:
			if (argc == 0)
				usage("htmplgen");
				usage("gohtmplgen");
			else
				usage(argv[0]);
		}
	}
	argc -= optind;
	argv += optind;

	if (out && (fp = fopen(out, "w")) == NULL)
		err(1, "can't open %s", out);

	if (argc == 0) {
		if (parse(fp, "/dev/stdin") == -1)
			goto err;
	} else {
		fputs("use fmt;\n", fp);
		fputs("use io;\n", fp);
		fputs("use htmpl;\n", fp);
		for (i = 0; i < argc; ++i)
			if (parse(fp, argv[i]) == -1)
				goto err;
	}

	if (ferror(fp))
		goto err;

	if (fclose(fp) == -1) {
		fp = NULL;
		goto err;
	}

	return 0;

err:
	if (fp)
		fclose(fp);
	if (out && unlink(out) == -1)
		err(1, "unlink %s", out);
	return 1;
}