Frage

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?

War es hilfreich?

Lösung

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

Andere Tipps

There doesn't appear to be a built in filter to get the physical base path.

http://jinja.pocoo.org/docs/templates/#list-of-builtin-filters

Here's how you could pass the current physical path.

import os


tmpl = env.get_template('index.html')
return tmpl.render(folder=os.path.dirname(__file__))

Hope this helps!

It's pretty simple, if you think about it, it's just tokenization using /, so for basename you split your string by slashes into a list, then get the last element from that list:

{{ mybin.split('/') | last }}

dirname is a bit more tricky:

{{ mybin.split('/')[:-1] | join('/') }}

Again, you explode the string by slashes, then take that list from the first item (:) until the penultimate item (-1), then join them back together.


Easy as pie, right? Jinja2 often drives me crazy, but at the same time it's an incredibly powerful and often really efficient language :)

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top