Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jinja2 basename or dirname from builtin filters?

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?

like image 694
719016 Avatar asked Mar 21 '14 15:03

719016


People also ask

What is Jinja2 template in Ansible?

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.

What does pipe mean in Ansible?

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.


1 Answers

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
like image 125
Steve E. Avatar answered Sep 24 '22 05:09

Steve E.