【问题标题】:Rendering Jinja2 inheritance渲染 Jinja2 继承
【发布时间】:2015-04-05 15:51:21
【问题描述】:

我想利用jinja2中继承的概念,将配置的不同部分分离成多个独立的子模板。

最终,让它适用于更复杂的层次结构,例如:

parent.jj2
  |_child1.jj2
  |   |_child11.jj2
  |   |
  |   |_child12.jj2
  |
  |_child2.jj2
      |_child21.jj2
      |
      |_child22.jj2

在这个例子中,我只使用了 2 个子模板:

parent.jj2 模板:

## Main file header
{% block child1 %}{% endblock %}
##
{% block child2 %}{% endblock %}
## Main file tail

child1.jj2 模板:

{% extends "parent.jj2" %}
{% block child1 %}
{% for i in list %}
child1 line {{ i }}
{% endfor %}
{% endblock %}

child2.jj2 模板:

{% extends "parent.jj2" %}
{% block child2 %}
{% for i in list %}
child2 line {{ i }}
{% endfor %}
{% endblock %}

我使用下面的渲染,子模板是单独渲染的,但是没有产生想要的结果:

使用 jinja2 加载器:

list1 = \
    [1,2,3]

list2 = \
    ['a','b','c']

loader = jinja2.FileSystemLoader(os.getcwd())
jenv = jinja2.Environment(loader=loader, trim_blocks=True,lstrip_blocks=True)

template = jenv.get_template('child1.jj2')
print template.render(list=list1)

template = jenv.get_template('child2.jj2')
print template.render(list=list2)

如何以这样的方式调用渲染,使主模板与单个文件中的子块一起渲染?

期望的结果:

## Main file header
child line1 1
child line1 2
child line1 3
##
child line1 a
child line1 b
child line1 c
## Main file tail

目前的结果:

## Main file header
child line1 1
child line1 2
child line1 3
##
## Main file tail

## Main file header
##
child line1 a
child line1 b
child line1 c
## Main file tail

【问题讨论】:

    标签: python-2.7 jinja2


    【解决方案1】:

    我使用 include 得到了想要的结果。

    渲染父模板,其中包含所有子模板

    parent.jj2:

    #Main file header
    {% include "child1.jj2" %}
    ##
    {% include "child2.jj2" %}
    #Main file tail
    

    child1.jj2

    {% block peceinterfaces %}
    {% for i in list[0] %}
    child1 line1 {{ i }}
    {% endfor %}
    {% endblock %}
    

    child2.jj2:

    {% block pepinterfaces %}
    {% for i in list[1] %}
    child2 line1 {{ i }}
    {% endfor %}
    {% endblock %}
    

    渲染父模板:

    list1 = \
        [1,2,3]
    
    list2 = \
        ['a','b','c']
    
    loader = jinja2.FileSystemLoader(os.getcwd())
    jenv = jinja2.Environment(loader=loader, trim_blocks=True,lstrip_blocks=True)
    
    template = jenv.get_template('parent.jj2')
    print template.render(list=[list1,list2])
    

    结果:

    #Main file header
    child1 line1 1
    child1 line1 2
    child1 line1 3
    ##
    child2 line1 a
    child2 line1 b
    child2 line1 c
    #Main file tail
    

    【讨论】:

      【解决方案2】:

      您可以在子模板顶部使用扩展

      {% extends "child1.jj2l" %}
      

      【讨论】:

      • #Garesh-shyara,这是不会产生预期结果的初始条件。
      猜你喜欢
      • 2016-01-19
      • 1970-01-01
      • 1970-01-01
      • 2014-02-14
      • 2018-04-23
      • 2016-06-24
      • 2023-03-24
      • 2015-04-14
      • 2012-06-04
      相关资源
      最近更新 更多