Skip to content

Template Children

Heliguy edited this page May 13, 2026 · 3 revisions

Often in GJS applications, you want to use UI files or Blueprint files to define a widget's structure declaratively. GObjectify streamlines the process of getting access to children widgets defined in these files.

Background - Template Children in Plain GJS

In plain GJS, getting access to template children requires specifying the children in the GObject.registerClass function, and requires declaring them as fields on the subclass.

class MyBox extends Gtk.Box {
	static {
		GObject.registerClass({
			Template: "resource:///org/example/ui/my_box.ui",
			TemplateChildren: ["title_label", "submit_button"],
		}, this)
	}

	declare _title_label: Gtk.Label
	declare _submit_button: Gtk.Button
}

This repetition and use of unsafe declare results it more error-prone code, as a typo could lead to uncaught runtime errors. GJS also requires template children be accessed with an underscore, which is easy to forget.

While GObjectify cannot prevent incorrect types from being supplied, it can reduce the repetition and verbosity, as well as enforcing the underscore prefix.

The GObjectify Way

@GClass()
class MyBox extends from(Gtk.Box, {
	_title_label: Child<Gtk.Label>(),
	_submit_button: Child<Gtk.Button>(),
}) {}

The subclass now knows about the _title_label and _submit_button fields, as well as their types. They are also typed to be read-only, so you can't accidentally override them with a different value. Template children are available in the constructor after the super() call. Additionally, you'll see a type-error if you do not name your template children with leading underscores.

Not that unfortunately, due to TypeScript limitations, GObjectify cannot mark template children as private, so they will be available to use outside of the class.

Clone this wiki locally