Pass variables from child template to parent in Jinja2

前端 未结 2 855
予麋鹿
予麋鹿 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)
    
    0 讨论(0)
  • 2021-01-07 18:34

    Ah. Apparently they won't be defined when they are passed through blocks. The solution is to just remove the block tags and set it up like so:

    parent.html:

    {% if bool_var %}
        {{ option_a }}
    {% else %}
        {{ option_b }}
    {% endif %}
    

    child.html:

    {% extends "parent.html" %}
    
    {% set bool_var = True %}
    {% set option_a = 'Text specific to this child template' %}
    {% set option_b = 'More text specific to this child template' %}
    
    0 讨论(0)
提交回复
热议问题