New Wagtail Course! 🥳 The Ultimate Wagtail Developers Course

Tutorial Wagtail Version: 2.x

Adding Custom StreamField Logic

There will be times when you need to provide multiple optional fields in a StreamField, and naturally we lean towards using logic in the template. In this video we're going to learn how to pull out template logic and use Python instead. In this example we'll be using a StructValue and StructBlock to return a single URL in the template even though the StreamField has a PageChooserBlock and a URLBlock (pick one and return it).

StreamFields are a great way to add customized content to your pages. It allows you to mix and match your content any way you like and that allows you to make some really unique page layouts.

But occasionally you'll run into issues where you need to give the admin a couple of options and display certain attributes in your template based on the data entered.

A good example of this is the typical PageChooserBlock vs URLBlock (or internal vs. external page urls).

If you have a button on a StreamField but you need to give the admin the ability to select an internal Wagtail Page or paste in a full external URL, you'll start writing custom logic in your template, like this:

``` {% if self.button_page %} {# Make a link from self.button_page.url #} {% elif self.external_page %} {# Make a link form self.external_page #} {% endif %} ```

Ideally you'd like to keep logic out of the template and use Python logic instead. So the above code can boil down to something much more simple and doesn't require template parsing. The ideal outcome would be this:

{{ self.url }}

In this lesson we're using a StructValue and a StructBlock to add additional logic to our StreamField template so the template engine doesn't need to do additional work (plus we can remove template logic making our templates easier to work with).

The Git Commit

Want the full code from this lesson? It's available for you 24/7 on GitHub for free, just follow this link:

Related tutorials

The Ultimate Wagtail Developers Course

This course covers everything from basic installation to advanced features like custom blocks and API integration, it's perfect for developers looking to enhance their skills with this powerful CMS.

Ultimate Wagtail Developers Course Logo