2017-06-29 15 views
0

ネストされたリストに「ノート」を表示しようとしています。各ノートにはparentIDという名前のプロパティがあり、それがネストされていることを示します。 Index.htmlと子アイテムを再帰的に検索してジンジャーにリストアップする

models.py

class Note(Model): 
    title = CharField() 
    tags = CharField() 
    content = TextField() 
    parentID = IntegerField(default=0) 

    class Meta: 
     database = db 

app.py

def getSubnotes(note): 
    note_id = note.id 
    subnotes = models.Note.select().where(models.Note.parentID == note_id) 
    return subnotes 

app.jinja_env.globals.update(getSubnotes=getSubnotes) 

は現在、私はこれを行うことにより、単一レベルの巣を達成しています

<div class="row"> 
<div class="medium-12 medium-centered"> 
    <ul> 
    {% for note in notes %} 
     {% if note.parentID == 0 %} 
     <li><a href="/n/{{note.getHash()}}">{{ note.title }}</a></li> 
     <ul> 
     {% for subnote in getSubnotes(note) %} 
     <li><a href="/n/{{subnote.getHash()}}">{{ subnote.title }}</a></li> 
     {% endfor %} 
     </ul> 
     {% endif %} 
    {% endfor %} 
    </ul> 
</div> 

私は、しかし、再帰的に単音のすべての子どもたちのノートを見つけ、それらをリストアップしたいと思いますので、巣の巣があります。

私は再帰的に(jinja docsから)神社に一覧表示する方法の例として、これを見てきました:

<ul class="sitemap"> 
{%- for item in sitemap recursive %} 
    <li><a href="{{ item.href|e }}">{{ item.title }}</a> 
    {%- if item.children -%} 
     <ul class="submenu">{{ loop(item.children) }}</ul> 
    {%- endif %}</li> 
{%- endfor %} 
</ul> 

は、しかし、私は.childrenが実際にあるかについて混乱しています。どのようにそれ自身または同じタイプのitemsを参照していますか?

これを再帰的に実行するにはどうすればよいですか、同じことを達成するためのより良い方法がありますか?

ご協力いただきありがとうございます。

答えて

1

ドキュメントの例では、item.childrenは、同じタイプのアイテムの繰り返し可能なものだと思います。 {{ loop(item.children) }}は、現在のループを反復可能なitem.childrenで実行し、ネストされたリストを作成します。

あなたは、この確認できます。だからあなたの例では、私はあなたがいる限り

<div class="row"> 
<div class="medium-12 medium-centered"> 
    <ul> 
    {% for note in notes recursive %} 
     {% if note.parentID == 0 %} 
     <li><a href="/n/{{note.getHash()}}">{{ note.title }}</a></li> 
     <ul> 
     {{ loop(getSubnotes(note)) }} 
     </ul> 
     {% endif %} 
    {% endfor %} 
    </ul> 
</div> 

ような何かを行うことができるはずだと思う

import jinja2 

templ = """ 
{%- for item in items recursive %} 
    {{item.name}} 
    {%- if item.children %} 
     {{- loop(item.children) }} 
    {%- endif %} 
{%- endfor %} 
""" 

items = [{'name': 'Bobby'}, 
     {'name': 'Jack', 
      'children': [ 
       {'name': 'Jake'}, 
       {'name': 'Jill'}]}, 
     {'name': 'Babby', 'children': []}] 

template = jinja2.Template(templ) 
print(template.render(items=items)) 

プリントアウト

Bobby 
Jack 
Jake 
Jill 
Babby 

getSubnotes(note)は、ノートにサブノートがない場合は空を返します。

関連する問題