Is there any way of doing a basename
or dirname
in jinja2 using only builtin filters? E.g. something like:
#!/usr/bin/python
import jinja2
mybin = '/my/favorite/full/path/foo'
t = jinja2.Template("my binary is {{ mybin }}")
print t.render()
t = jinja2.Template("my basename is {{ mybin|basename() }}")
print t.render()
t = jinja2.Template("my dirname is {{ mybin|dirname() }}")
print t.render()
1
Any ideas?
Jinja2 templates are simple template files that store variables that can change from time to time. When Playbooks are executed, these variables get replaced by actual values defined in Ansible Playbooks. This way, templating offers an efficient and flexible solution to create or alter configuration file with ease.
With the pipe character you pass a value to a filter. There are numerous Jinja 2 filters but Ansible brings some additional filters. The term filter might be confusing at times because all the filters work very differently.
If you found this question & are using Ansible, then these filters do exist in Ansible.
To get the last name of a file path, like ‘foo.txt’ out of ‘/etc/asdf/foo.txt’:
{{ path | basename }}
To get the directory from a path:
{{ path | dirname }}
Without Ansible, it's easy to add custom filters to Jinja2:
def basename(path):
return os.path.basename(path)
def dirname(path):
return os.path.dirname(path)
You register these in the template environment by updating the filters dictionary in the environment, prior to rendering the template:
environment.filters['basename'] = basename
environment.filters['dirname'] = dirname
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With