Search code examples
python-2.7jinja2

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?


Solution

  • 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