If Statements with Twig Tests

Video loading...

  • 0:00
    Twig Templating If Statements with Twig Tests
  • 0:04
    with Leanna Pelham
  • 0:09
    But when we tried the Contact page, it blows up.
  • 0:12
    We're not passing a background color in the include call
  • 0:15
    in contact.twig, so Twig gets angry.
  • 0:19
    We can, of course, pass this variable to the template.
  • 0:22
    But instead, let's check to see if the variable is defined
  • 0:25
    in the _banner.twig template and default to light blue if it's not.
  • 0:30
    To do this, we can use an "if" statement
  • 0:32
    and the special defined test.
  • 0:35
    Let's also see another new Twig tag called
  • 0:37
    set, which sets a new variable.
  • 0:56
    Try out both pages in the browser.
  • 1:00
  • 1:04
    Let's look, again, at the "if background is defined."
  • 1:07
    Normally, an "if" statement says something like "if foo
  • 1:10
    !='bar'" or "if isPublished == true."
  • 1:15
    That all works totally fine in Twig.
  • 1:17
    But in addition, to "==" and "!=" and the others, you can say "is"
  • 1:21
    and follow that by a word like "defined," "even,"
  • 1:24
    "odd," "empty," or several other words.
  • 1:27
    These are called "tests," and they're listed, once again,
  • 1:30
    right back on the main documentation page of the Twig website.
  • 1:36
    For example, instead of using the "length" filter
  • 1:39
    and seeing if the number of items in the products collection is 0,
  • 1:42
    we could say "if products is empty."
  • 1:48
    If, for some reason, we wanted to know if the total number
  • 1:50
    of products were even, we could use the "length" filter
  • 1:53
    to get that number and then check that the number is
  • 1:56
    even by using the even test.
  • 1:58
    The tests are easy to use and can shorten the code needed
  • 2:01
    to do some things, so don't forget about them.
  • 2:15
    You can also negate a test by using the "not" keyword.
  • 2:18
    We can use this to simplify our code from earlier.
  • 2:30
  • 2:31
    At this point, you know a lot of tools in Twig.
  • 2:33
    Let's keep going and learn some more.
Loading ...

If Statements with Twig Tests


In our last tutorial we have things set up to include a new template, but we are currently getting an error, due to not passing the correct variable. In this tutorial we'll see how to fix this problem by adding a "defined" test to our code, which will check to see if the variable is defined in the _banner.twig template, and default to "lightblue" if it is not.

Log in or sign up to download companion files.
Additional resources: