YAML Macros

Macros are used to create reusable snippets of code that can be used throughout a document. Macros are similar to templates, but they are designed to be more flexible and can contain placeholders that can be replaced with specific values. Here is an example of how to use a YAML macro:

# Define a macro for a person
%person_macro(name, age):
  name: {{ name }}
  age: {{ age }}

# Use the person macro in two places
  person: !<person> ["John", 30]
  city: New York

  person: !<person> ["Jane", 25]
  city: San Francisco

In this example, the “%person_macro” macro is defined with two parameters, “name” and “age”. The macro contains a YAML dictionary with the “name” and “age” keys, and the values for those keys are defined using the “{{ }}” syntax. This syntax is used to indicate a placeholder that can be replaced with a specific value when the macro is used.

The “first” and “second” dictionaries both use the “!<person>” tag to indicate that the “person” key should be replaced with the contents of the “person_macro”. The contents of the macro are defined using the “[” and “]” syntax, with the values for the “name” and “age” parameters specified in the order they were defined.

When the document is processed, the placeholders in the macro are replaced with the specific values provided when the macro is used. This allows for the creation of reusable code snippets that can be customized based on the specific needs of the document.

Follow us on social media
Follow Author