Pass variables from child template to parent in Jinja2

前端 未结 2 872
予麋鹿
予麋鹿 2021-01-07 17:48

I want to have one parent template and many children templates with their own variables that they pass to the parent, like so:

parent.html:

{% block          


        
2条回答
  •  耶瑟儿~
    2021-01-07 18:18

    If Nathron's solution does not fix your problem, you can use a function in combination with a global python variable to pass a variable value.

    • Advantage: The variable's value will available in all templates. You can set the variable inside a block.
    • Disadvantage: More overhead.

    This is what I did:

    child.j2:

    {{ set_my_var('new var value') }}
    

    base.j2

    {% set my_var = get_my_var() %}
    

    python code

    my_var = ''
    
    
    def set_my_var(value):
        global my_var 
        my_var = value
        return '' # a function returning nothing will print a "none"
    
    
    def get_my_var():
        global my_var 
        return my_var 
    
    # make functions available inside jinja2
    config = { 'set_my_var': set_my_var,
               'get_my_var': get_my_var,
               ...
             }
    
    template = env.get_template('base.j2')
    
    generated_code = template.render(config)
    

提交回复
热议问题