Jinja2遍历python列表以返回xml

时间:2019-07-18 14:38:06

标签: python xml python-3.x jinja2

我有一个返回['a','b','c']的python列表,我想使用此列表通过Jinja2模板分别显示每个项目。

我尝试使用batch(1):

{% for resource in resourcelist|batch(1) %}
            <file {{ resource }} >
{% endfor %}

但是,它仍然以列表形式返回答案:

文件['a','b',     'c']>

我使用过endif,但是无法运行代码。

具有Jinja2模板的xml文件是:

<resources>
<resource identifier="resource" type="webcontent" adlcp:scormtype="sco" 
href="{{starting_resource}}">
{% for resource in resourcelist %}
            <file {{ resource }} >
{% endfor %}
</resource>

我当前得到的输出是:

<resource identifier="resource" type="webcontent" 
adlcp:scormtype="sco" href="df/res/test.hml">

        <file df/res/test.hml >

        <file ['a', 'b', 'c'] >

</resource>

python代码:

mylist = [index, all_resources]

output = template.render(starting_resource = index, resourcelist = 
mylist)

我想要的输出是:

<resource identifier="resource" type="webcontent" 
adlcp:scormtype="sco" href="df/res/test.hml">

        <file df/res/test.hml >

        <file ['a'] >

        <file ['b'] >

        <file ['c'] >

</resource>

建议,我是Jinja模板的新手。

我的目标是能够从目录中提取所有文件,并使用XML页面中的Jinja2模板列出它们。

1 个答案:

答案 0 :(得分:1)

请考虑避免在Python中重复分配 index ,而在Jinja中只需两次引用 starting_resource 。下面还正确地使用了属性和结束标记来形成格式正确的XML输出。

Python 脚本(不需要mylist变量)

output = template.render(starting_resource = index, resourcelist = all_resources)

Jinja 模板

<resources>
    <resource identifier="resource" type="webcontent" adlcp:scormtype="sco" 
              href="{{starting_resource}}">
            <file href="{{starting_resource}}" /> 
      {% for resource in resourcelist %}
            <file href="{{resource}}" />
      {% endfor %}
    </resource>
</resources>
相关问题