Skip to content

Create apply_classes_to_streamfield_elements.md #14

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions wagtail/apply_classes_to_streamfield_elements.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
# Applying Tailwind classes to Wagtail StreamField elements

## Links

- [How to use StreamField for mixed content — Wagtail Documentation 6.1.1 documentation](https://docs.wagtail.org/en/stable/topics/streamfield.html)

## Use case

I have a Wagtail StreamField. This is the one from the [docs]((https://docs.wagtail.org/en/stable/topics/streamfield.html)):

```python
from django.db import models

from wagtail.models import Page
from wagtail.fields import StreamField
from wagtail import blocks
from wagtail.admin.panels import FieldPanel
from wagtail.images.blocks import ImageChooserBlock

class BlogPage(Page):
author = models.CharField(max_length=255)
date = models.DateField("Post date")
body = StreamField([
('heading', blocks.CharBlock(form_classname="title")),
('paragraph', blocks.RichTextBlock()),
])

content_panels = Page.content_panels + [
FieldPanel('author'),
FieldPanel('date'),
FieldPanel('body'),
]
```

I need the elements of the StreamField, like the `heading` and the `paragraph`, to have different Tailwind classes applied to them.

## Solution: Apply a CSS class, then implement the Tailwind classes in the CSS file

> Note: This TIL assumes your Tailwind setup is already configured and working. I wish I had written that TIL when I did that, but I did not.

In my template, I added the class `custom-page` to where I render the `body`:

```html
{% load wagtailcore_tags %}

{% for block in page.body %}
{% if block.type == "heading" %}
<h2 class="custom-page">{{ block.value }}</h2>
{% elif block.type == "paragraph" %}
<p class="custom-page">{{ block.value|richtext }}</h2>
{% endif %}
{% endfor %}
```