Reputation: 122
I have added 4 paragraph blocks in a streamfields. When looping over the paragraph block, it show all 4 paragraph in separate
tags. How can I only limit it to the first paragraph block? I tried using this solution:
{% if forloop.counter0 == 0 %}
<p>{{block.value}}</p>
{% endif %}
But the problem was that its only possible when the paragraph field is placed in the first order. For example, there can be 3 images before the first paragraph which makes the possible solution void.
blog/models.py
class BlogPage(Page):
body = StreamField([
('paragraph', blocks.RichTextBlock()),
('image', ImageChooserBlock()),
])
content_panels = Page.content_panels + [
StreamFieldPanel('body')
]
blog_page.html
{% for block in page.body %}
{% if block.block_type == 'paragraph' %}
<p>{{block.value.0}}</p> <!-- Another attempt at trying to get single paragraph -->
{% endfor %}
Upvotes: 0
Views: 498
Reputation: 25317
It's often easier to do this sort of logic in Python code inside the model, rather than trying to shoehorn it into Django template notation:
class BlogPage(Page):
body = StreamField([
('paragraph', blocks.RichTextBlock()),
('image', ImageChooserBlock()),
])
content_panels = Page.content_panels + [
StreamFieldPanel('body')
]
def first_paragraph(self):
for block in self.body:
if block.block_type == 'paragraph':
return block.value
Then use <p>{{page.first_paragraph}}</p>
in your template.
Upvotes: 3