Learn Wagtail CMS Course

Adding Custom StreamField Logic

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: https://github.com/CodingForEverybody/learn-wagtail/commit/4218b53508dc2697dcf032c0f5c56dce38cb929a