37

I'd like to detect if a Jinja2 template block content is empty or not. Something like this:

{% block foo %}{% endblock foo %}{% if foo %} - {% endif %}Blah Blah Blah

What I want is conditional text outside the block definition itself. In the contrived example, I want to be able to insert a conditional string - after the block if and only if the block has been overridden and is not empty.

Is this possible?

Inactivist
  • 9,997
  • 6
  • 29
  • 41

1 Answers1

56

Simply call the block:

{% if self.foo() %} - {% endif %}
Sean Vieira
  • 155,703
  • 32
  • 311
  • 293
  • I am not worthy! Thanks, that works great. Did I miss that in the docs, or is it one of those 'pro tips' items...? – Inactivist Sep 10 '13 at 14:23
  • 2
    @Inactivist - it is buried in the [template designer docs](http://jinja.pocoo.org/docs/templates/#child-template) "If you want to print a block multiple times you can however use the special self variable and call the block with that name". – Sean Vieira Sep 10 '13 at 15:08
  • 2
    Note that it's important for the block in question to be completely empty. I had a newline in mine that was evaluating to the empty string but still counted as truthy. – Brian Peterson Nov 19 '15 at 20:43
  • 5
    @BrianPeterson: Use the [`trim`](http://jinja.pocoo.org/docs/dev/templates/#trim) filter to ignore leading and trailing whitespace: `{% if self.foo() | trim %} - {% endif %}`. – Florian Brucker Feb 23 '16 at 13:49