Nested IF statements with Movable TYpe

Sep 22, 2009 12:10 · 362 words · 2 minute read code development movabletype mt php

One of the - ahem - undocumented features of Movable Type is a certain estotericness about the way it interprets Boolean logic within template tags. That’s a polite way of saying it’s more-or-less completely unpredictable, which can lead to much wailing and gnashing of teeth during template development.

Fortunately, there’s a workaround, an example of which is below. It comes at a computational cost, because you’re using PHP to fill in for MT’s deficiencies - but if you’re using static templates, then that cost is only really incurred as the templates are rebuild

This code assumes that you’re checking for two conditions - the presence of a custom field called “magazine_issue” that contains “Issue 19”, and a second custom field called “entrydatasource” which should contain the value “DVD”.

There’s a PHP loop inside an MT loop here - lines 1 and 2 set up the MT part, and iterates across the entries in the blog looking for those which have the field “magazine_issue” set to “Issue 19”.  (The MT:Entries tag is split across two lines for readability here, rather than any other reason.) Then those entries are passed one by one to the inner PHP code.

Line 5 places whatever’s in mt:entrydatasource into $source, relying on the fact that MT tags are parsed first, so by the time the PHP code gets executed that tag has been replaced by the value inside it.

Then lines 7 to 11 run a PHP if statement to check that the content contains “DVD”, and executes the mt:include tag if that’s the case.  The positioning of the ?> and <?php braces allow you to place MT code within the PHP loop, but not to have the PHP parser attempt to interpret it.

If the if statement doesn’t evaluate to true, then the contents won’t be executed and the include statement won’t be executed.   Obviously the include could be replaced by pretty much any MT tags that are valid within the context of an MT:Entries loop, or whatever arbitrary PHP you wanted.

It’s slightly hacky, and does come with a processing overhead - but sometimes a hack is the only way to get out of the problem.