Module hcl::template

source ·
Expand description

Types to represent the HCL template sub-language.

When parsing an HCL document, template expressions are emitted as TemplateExpr (as the TemplateExpr variant of the Expression enum) which contains the raw unparsed template expressions.

These template expressions can be further parsed into a Template which is composed of literal strings, template interpolations and template directives.

Refer to the HCL syntax specification for the details.

§Example

Parse a TemplateExpr into a Template:

use hcl::Template;
use hcl::expr::{TemplateExpr, Variable};

let expr = TemplateExpr::from("Hello ${name}!");
let template = Template::from_expr(&expr)?;

let expected = Template::new()
    .add_literal("Hello ")
    .add_interpolation(Variable::new("name")?)
    .add_literal("!");

assert_eq!(expected, template);

It is also possible to use the template sub-language in a standalone way to parse template strings directly:

use hcl::Identifier;
use hcl::expr::Variable;
use hcl::template::{ForDirective, Strip, Template};
use std::str::FromStr;

let raw = r#"
Bill of materials:
%{ for item in items ~}
- ${item}
%{ endfor ~}
"#;

let template = Template::from_str(raw)?;

let expected = Template::new()
    .add_literal("\nBill of materials:\n")
    .add_directive(
        ForDirective::new(
            Identifier::new("item")?,
            Variable::new("items")?,
            Template::new()
                .add_literal("\n- ")
                .add_interpolation(Variable::new("item")?)
                .add_literal("\n")
        )
        .with_for_strip(Strip::End)
        .with_endfor_strip(Strip::End)
    )
    .add_literal("\n");

assert_eq!(expected, template);

§Template evaluation

The eval module provides evaluation capabilities for templates and expressions. See the module-level documentation for examples.

Structs§

  • The template for directive is the template equivalent of the for expression, producing zero or more copies of its sub-template based on the elements of a collection.
  • The template if directive is the template equivalent of the conditional expression, allowing selection of one of two sub-templates based on the condition result.
  • An interpolation sequence evaluates an expression (written in the expression sub-language), converts the result to a string value, and replaces itself with the resulting string.
  • The main type to represent the HCL template sub-languange.

Enums§

  • A template directive that allows for conditional template evaluation.
  • An element of an HCL template.
  • Controls the whitespace strip behaviour for template interpolations and directives on adjacent string literals.