Skip to content

Instantly share code, notes, and snippets.

@markan
Created November 20, 2017 21:24
Show Gist options
  • Save markan/1d1f6c7e4b1c4cd5e75d361a58815675 to your computer and use it in GitHub Desktop.
Save markan/1d1f6c7e4b1c4cd5e75d361a58815675 to your computer and use it in GitHub Desktop.

Using Partials in Habitat

I'm writing this up because it took me way too long to figure this out, even if it's obvious in retrospect.

Habitat uses the handlebars-rust library, (https://github.com/sunng87/handlebars-rust) which is an implementation of the handlebarsjs (http://handlebarsjs.com/) templating language. Those docs are super helpful, but it took me a few passes to piece together what I needed to do.

Including a partial

Habitat supports the {{> filename}} syntax, with a minor quirk. Habitat reads all of the files in the config directory, and registers them as handlebars templates. So any file in that directory will both be rendered, and be available as a partial in other files. I put a handlebars comment in my partials to distinquish them.

Making a partial distinct with with

If all you want to do is include some boilerplate, you are done. But most likely you would like some variable content as well. By default, the partial gets the same scope as it's parent.

That can be changed with the ```with`` statement

If your default.toml has something like: [http] port = 8080 is_ssl = false [https] port = 8443 is_ssl = true

You can include a partial bracked by a with statement like this: {{#with cfg/http}} {{> chef_http_lb_common }} {{~/with}}

And the variables port and is_ssl will be available in the partial. The with changes the scope we are evaluating to the specified path, in this case cfg/http.

However, there's one trick; you've changed the scope for all variables. Say your partial had a reference to pkg.path; now it won't resolve because you've changed the scope. However you can use the ../ syntax to reach into the surrounding scope. Here we'd replace {{pkg.path}} with {{../pkg.path}}.

That last bit was the part that took me the longest to figure out; much thanks to the examples in the rust-handlebars project for the insight.

As a final note, with statements can be nested, so you might need to do multiple ../ sequences to get to your variables.

Future research

  • Handlebars has an absolute path notation with @, but it doesn't look like handlebars-rust supports it, or at least it doesn't seem to be tested. I'd like to delve into that more deeply.

  • I've not played with recursive partials yet. That could be fun.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment