xuhdev
xuhdev

Reputation: 9390

Jinja2 api: how to get the inherited template of a template?

A template file:

{% extends "base.html" %}

The templates are loaded like the following:

env = Environment(loader = FileSystemLoader(['_templates']))
template = env.get_template('test.html')

How can I get the parent template object, i.e., the template of "base.html", from the template variable?

Upvotes: 3

Views: 116

Answers (1)

r-m-n
r-m-n

Reputation: 15120

You can parse template source and find Extends node. See AST documentation for details

from jinja2.nodes import Extends

env = Environment(loader = FileSystemLoader(['_templates']))
template_source = env.loader.get_source(env, 'test.html')[0]
parsed_template = env.parse(template_source)
extends_node = parsed_template.find(Extends)
parent_name = extends_node.template.value
parent_template = env.get_template(parent_name)

Upvotes: 3

Related Questions