text_template
text_template renders a Go text/template template during build evaluation and returns its output as a Starlark string.
Load it from API version 1:
load("@text@1", "text_template")
Arguments
| Argument | Required | Description |
|---|---|---|
template | Yes | Go template source string. |
data | No | Template data. Supports None, booleans, strings, integers, floats, lists, tuples, and dictionaries with string keys. Defaults to None. |
missing_key | No | Missing map key behavior: "error" fails, "zero" uses map element zero value, and "keep" uses Go template default behavior. Defaults to "keep". |
trim | No | Strip leading and trailing whitespace from final output. Defaults to False. |
funcs | No | Dictionary mapping template function names to Starlark callables. |
name | No | Template name shown in parse and execution diagnostics. Defaults to "text_template". |
dedent | No | Remove indentation shared by every nonblank template source line and the first blank line. This preserves the newline before a closing multiline-string delimiter. Defaults to False. |
With Starlark dictionaries, "zero" and "keep" both usually print <no value> because dictionary values can have mixed types. Use "error" when every referenced key must exist.
Example
load("@text@1", "text_template")
result = text_template(
"""
Hello {{ .user.name }},
{{ if .user.is_admin }}
You have administrator access.
{{ else }}
You have standard access.
{{ end }}
Projects:
{{ range .projects }}
- {{ .name }}{{ if .active }} (active){{ end }}
{{ end }}
""",
data = {
"user": {
"name": "Alice",
"is_admin": True,
},
"projects": [
{"name": "Atlas", "active": True},
{"name": "Beacon", "active": False},
],
},
dedent = True,
)
Custom Functions
Template function arguments are converted back to Starlark values. Return values are converted to template values.
def upper(value):
return value.upper()
message = text_template(
"Hello {{ upper .name }}",
data = {"name": "Alice"},
funcs = {"upper": upper},
name = "greeting",
)