Last active
August 29, 2015 14:03
-
-
Save wooyek/8d4c37d684a5ba38b8c1 to your computer and use it in GitHub Desktop.
A jinja2 extension allowing to import relative template names
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding=utf-8 | |
# Created 2014 by Janusz Skonieczny | |
from jinja2.ext import Extension | |
import re | |
class RelativeInclude(Extension): | |
"""Allows to import relative template names""" | |
tags = set(['include2']) | |
def __init__(self, environment): | |
super(RelativeInclude, self).__init__(environment) | |
self.matcher = re.compile("\.*") | |
def parse(self, parser): | |
node = parser.parse_include() | |
template = node.template.as_const() | |
if template.startswith("."): | |
# determine the number of go ups | |
up = len(self.matcher.match(template).group()) | |
# split the current template name into path elements | |
# take elements minus the number of go ups | |
seq = parser.name.split("/")[:-up] | |
# extend elements with the relative path elements | |
seq.extend(template.split("/")[1:]) | |
template = "/".join(seq) | |
node.template.value = template | |
return node |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Read more about extensions here:
http://jinja.pocoo.org/docs/extensions/?highlight=extensions#module-jinja2.ext