Textpattern tips, tutorials and code snippets

Conditional tag attributes with etc_query

The construction of complex conditional queries with Textpattern can quickly turn into a nightmare. To give an example, suppose you are running a music website, each article corresponding to a song. You can store a song’s composer, singer, album and so on in custom fields, and you’d like to give visitors the possibility to filter articles by some of these fields, with an url string like:

...&composer=Lennon&album=Rubber+Soul

We admit you have imported user request into corresponding txp variables (with, say, adi_gps), so you can issue a query like:

<txp:article_custom
   composer='<txp:variable name="composer" />'
   album='<txp:variable name="album" />'
/>

Constructing your variables

The problem is that if some field (say, composer) is not specified by the visitor, this will return only the songs without composer, i.e. probably an empty list. So you have to construct a conditional monster like:

<txp:if_variable name="composer" value="">
<txp:if_variable name="album" value=""> 
   <txp:article_custom />
<txp:else />
   <txp:article_custom album='<txp:variable name="album" />' />
</txp:if_variable>
<txp:else />
<txp:if_variable name="album" value="">
   <txp:article_custom composer='<txp:variable name="composer" />' />
<txp:else />
   <txp:article_custom composer='<txp:variable name="composer" />' album='<txp:variable name="album" />' />
</txp:if_variable>
</txp:if_variable>

Construct the tag using etc_query

Every additional variable doubles its size, so imagine what it would be for 3 or more search criteria! Fortunately, etc_query has the ability to conditionally construct a tag using {$?(if|then|else)} tokens. La cerise sur le gâteau – it can import GET/POST data too, so the complete solution is as simple as:

<txp:etc_query globals="_GET,_POST">
   <txp:article_custom
       {$?({?composer}|composer="{?composer}"|)}
       {$?({?album}|album="{?album}"|)}
   />
</txp:etc_query>
Use Textile help to style your comments