04_overriding_a_base_template_variable 

Send to Kindle
home » snippets » python » jinja2 » example » 04_overriding_a_base_template_variable



#!/usr/bin/env python
# -*- coding: utf-8 -*-


# Sample output:
#
#    ----------------------------------------
#    A: Foo is: set from A
#    A: Foo is: set from A
#    ----------------------------------------
#    
#    
#    ----------------------------------------
#    A: Foo is: set from B
#    B: Foo is: set from B
#    ----------------------------------------


from __future__ import print_function

import jinja2


JINJA_TEMPLATES = dict()

JINJA_TEMPLATES["A"] = r'''
{%- set foo = "set from A" if not foo else foo -%}

{% block only_in_base -%}
A: Foo is: {{foo}}
{% endblock only_in_base -%}

{% block overridden_in_inherited -%}
A: Foo is: {{foo}}
{% endblock overridden_in_inherited -%}
'''

JINJA_TEMPLATES["B"] = r'''
{%- set foo = "set from B initially" -%}
{%- set foo = "set from B" -%}
{%- extends "A" -%}

{% block overridden_in_inherited -%}
B: Foo is: {{foo}}
{% endblock overridden_in_inherited -%}
'''

jinja_env = jinja2.Environment(loader=jinja2.DictLoader(JINJA_TEMPLATES))

def main(argv):
  sep_line = "-"*40
  print("\n%s\n%s%s\n" % (sep_line, jinja_env.get_template("A").render(), sep_line))
  print("\n%s\n%s%s\n" % (sep_line, jinja_env.get_template("B").render(), sep_line))


if __name__ == "__main__":
  import sys
  main(sys.argv)