Benos Benos -3 years ago 138
Python Question

How to include context variable in a wagtail cms field?

I am looking for a way to render a variable that will be available in the context of the the page where the cms page will be rendered.

I have in the context the logged in user and I also have the last transaction he made on the website.

I would like the text in the rich text field in Wagtail to be like this so that the marketing team can tweak the copy.

Hello ||firstname|| thanks for your purchase. ||productname|| will be
shipped to you soon. The expected delivery date is

To be less confusing I replace the double brackets by double pipes to show that the templating system does not need to be django templates for those ones. Simple templating is enough maybe using
I think I can achieve this by doing:

  1. A stream field that would have blocks of rich text field and a custom block with the possible context variable they can use

  2. A custom render function that would regex and replace the merge tags in the rich text block with the context values

  3. Create a new filter for simple templating. ex: {{ page.body|richtext|simpletemplate }}

Is there any more obvious way or out of the box way to do templating from within a rich text field?

Answer Source

It would be clunky with a separate streamfield block for each inserted context variable. You'd have to override the default rendering which wraps elements in div tags. However I like that it is more foolproof for the editors.

I've done something like the custom rendering before, but with simple TextFields for formatting special offer code messages. Wagtail editors were given the following help_text to illustrate:

valid_placeholders = ['offer_code', 'month_price']
template_text = models.TextField(
    help_text="Valid placeholder values are: {all_valid}. Write as {{{example}}}".format(
        all_valid=", ".join(valid_placeholders),

This rendered as Valid placeholder values are: offer_code, month_price. Write as {{offer_code}}.

Then in the view:

template_keys = [i[1] for i in Formatter().parse(template_text)]

…and continued rendering from there. Remember to validate the field appropriately using the above Formatter().parse() function too.

I used Django's template formatting rather than Python's string.format() because it fails silently, but you could go with string.format() if cleaned adequately.

The custom template filter would feel easiest to me, so I'd start with that approach and switch to a custom render function if I ran into hurdles.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download