caller

The caller variable takes a bit more explaining. A macro can call out to another macro. This can be useful if the same chunk of the template will be used multiple times, but part of the inside changes more than what could easily be passed as a macro parameter. The caller variable isn't exactly a variable; it's more of a reference back to the call to get the contents of that calling macro.

Let's update our template to demonstrate its usage:

{% macro test() -%}
The text from the caller follows: {{ caller() }}
{%- endmacro -%}
{% call test() -%} This is text inside the call {% endcall -%}

The rendered result will be as follows:

A call to a macro can still pass arguments to that macro; any combination of arguments or keyword arguments can be passed. If the macro utilizes varargs or kwargs, then extras of those can be passed along as well. Additionally, a macro can pass arguments back to the caller too! To demonstrate this, let's create a larger example. This time, our example will generate a file that's suitable for an Ansible inventory:

{% macro test(group, hosts) -%} 
[{{ group }}] 
{% for host in hosts -%} 
{{ host }} {{ caller(host) }} 
{%- endfor -%} 
{%- endmacro -%}  
{% call(host) test('web', ['host1', 'host2', 'host3']) -%} 
ssh_host_name={{ host }}.example.name ansible_sudo=true 
{% endcall -%}  
{% call(host) test('db', ['db1', 'db2']) %} 
ssh_host_name={{ host }}.example.name 
{% endcall -%}

Once rendered, the result will be as follows:

We called the test macro twice, once per group we wanted to define. Each group had a subtly different set of host variables to apply, and those were defined in the call itself. We saved typing by having the macro call back to the caller, passing along the host from the current loop.

Control blocks provide programming power inside of templates, allowing template authors to make their templates efficient. The efficiency isn't necessarily in the initial draft of the template; instead, the efficiency really comes into play when a small change to a repeating value is needed.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.134.78.106