2017-05-24 37 views
1

您好,我目前對django/wagtail是新手。我正在研究顯示以前和當前工作/職位的關於頁面。由於經驗數量不受限制,我已經完成了位置流場塊。這是我的模型的代碼。如果booleanBlock爲True,則以某種方式渲染streamfield塊

#Create experience block 
class ExperienceBlockStruct(StructBlock): 
    position_title = CharBlock(help_text="Enter a previous position title.") 
    description = CharBlock(help_text="Job description") 
    current_position = BooleanBlock(required=False, help_text="Check if 
    current position") 

class Meta: 
    template = 'blocks/experience_block.html' 


class ExperienceBlock(StreamBlock): 
    experience = ExperienceBlockStruct(icon="form") 

這裏是我使用模型

class About(Page): 
    profile_pic = "some image reduced code bc it currently works" 
    bio = RichTextField(blank=True) 
    resume = "some document reduced code bc it currently works" 
    experience = StreamField(ExperienceBlock()) 
    content_panels = Page.content_panels + [ 
     ImageChooserPanel('profile_pic'), 
     FieldPanel('bio'), 
     DocumentChooserPanel('resume'), 
     StreamFieldPanel('experience'), 
    ] 

的頁面現在我遇到的問題是如何渲染塊,其中current_position = True在不同的區域比那些沒有。 我試了

templates/about.html 
{% for block in page.experience %} 
    {% if block.current_position %} 
    {% include_block block %} 
    {% endif %} 
{% endfor %} 

但是這並沒有渲染任何東西。我也試過

<div class="experience"> 
    {% if value.current_position %} 
    {{ value.position_title }} 
    {% else %} 
    {{ value.position_title }} 
    {% endif %} 
</div> 

但是,它爲每個塊創建一個新的div。我想實現的是一樣的東西在blocks/experience_block.html

<div> 
    Current position(s): {% blocks with current_postion == True %} 
</div> 

<div> 
    Past position(s): {% blocks with current_postion == False %} 
</div> 

我怎麼可能去實現這樣的事情?

回答

0

你的第一個模板片斷幾乎是正確的 - 你只需要檢查block.value.current_position而非block.current_position

{% for block in page.experience %} 
    {% if block.value.current_position %} 
     {% include_block block %} 
    {% endif %} 
{% endfor %} 

這是因爲遍歷page.experience給你一個系列BoundBlock對象告訴你block_type(總是'experience'的在你的情況)與塊值一起。有關更詳細的解釋,請參閱BoundBlocks and values

你可以做同樣的事情在你的experience_block.html模板(使用{% for block in value %}而非{% for block in page.experience %}) - 但請注意的Meta模板定義需要去ExperienceBlock而不是ExperienceBlockStruct,因爲這是可以訪問完整的一個列表循環,而不是單個記錄。

爲了使事情變得更整潔,我建議在該區塊定義get_context方法,讓你在做Python代碼中的數據操作,而不是在模板中...

class ExperienceBlock(StreamBlock): 
    experience = ExperienceBlockStruct(icon="form") 

    def get_context(self, value, parent_context=None): 
     context = super(ExperienceBlock, self).get_context(value, parent_context=parent_context) 
     context['current_positions'] = [block for block in value if block.value.current_position] 
     context['past_positions'] = [block for block in value if not block.value.current_position] 
     return context 

    class Meta: 
     template = 'blocks/experience_block.html' 

這將使模板上的變量current_positionspast_positions可用。