Object References

Object references are specific to Haml syntax. They are not supported by Slim or EGO templates.

An object reference is a special object in Go that can provide either id and/or class attributes to an element.

@haml ArticleCard(article Article) {
	%div[article]
		%h1.article-title= article.Title
		%p= article.Content
}

In this example we used the article value as an object reference to the div element. Here is how this might render out:

<div id="article_article-123" class="article">
  <h1 class="article-title">The Title</h1>
  <p>The content of the article</p>
</div>

The article value we used in the example has implemented the following two methods:

func (a Article) ObjectID() string {
  return fmt.Sprintf("article-%d", a.ID)
}

func (a Article) ObjectClass() string {
  return "article"
}

Anything that implements func ObjectID() string can be used to provide an id attribute to an element. Likewise, anything that implements func ObjectClass() string can be used to provide a class attribute to an element. A type can implement either method on its own; GoHT only adds the attribute that the value actually supports.

When a value implements both methods, GoHT builds the id from the class and the ID joined with an underscore, class_id, rather than the bare ID alone. That is why the example above renders id="article_article-123" instead of id="article-123": the id includes the article class as a prefix.

If a value implements only ObjectID, the id attribute is the plain, unprefixed value. GoHT still renders an empty class="" attribute in this case, since the object reference syntax always sets up a class attribute even when ObjectClass isn’t implemented.

type Widget struct {
  Slug string
}

func (w Widget) ObjectID() string {
  return "widget-" + w.Slug
}
%div[widget]

renders as:

<div id="widget-sale" class="">

Prefixes

We can also provide a prefix that will be used for the class and id attributes, added in front of the class (if any).

@haml ArticleCard(article Article) {
	%div[article, "stunning"]
		%h1.article-title= article.Title
		%p= article.Content
}

renders as:

<div id="stunning_article_article-123" class="stunning_article">
  <h1 class="article-title">The Title</h1>
  <p>The content of the article</p>
</div>

The prefix doesn’t have to be a string literal. A Go variable works too:

@haml ArticleCard(article Article, prefix string) {
	%div[article, prefix]
		%h1.article-title= article.Title
		%p= article.Content
}