Looping over a List of Numbered Custom Fields in Movable Type

| No Comments | No TrackBacks |
Suppose you stored some information in a series of custom fields (attached to an entry) that all have the same name, except for an incrementing number.  Something like my_field_1, my_field_2, my_field_3, all the way up to my_field_20.  And that you had to display all this information, sequentially.  This is what I had to do earlier today, and here is how I did it.
I could just use the <mt:entrycustomfields> tag to loop over all available custom fields, but the order would not be guaranteed and  I would have needed to filter out other custom fields as well.

Instead, I used the <mt:for> tag to create a loop, and then a combination of <mt:setvarblock> and the mtevalregex_replace global modifiers.

<mt:for from="1" to="20">
<mt:setvarblock name="thetag"><foobar:entrydatamy_field_<mt:var name="__index__">></mt:setvarblock>
<mt:var name="thetag" regex_replace="/foobar/","mt" mteval="1">
</mt:for>

Here is how this works: the <mt:for> loop sets the __index__ variable to all numbers from 1 to 20, one after the other.  The next line will store following string in the $thetag variable: "<foobar:entrydatamy_field_x>", where x is one of these numbers.  The third line replaces the 'foobar' with 'mt' so we get a valid Movable Type tag, and the 'mteval' modifier will make sure the contents of the variable get interpreted as a Movable Type tag, resulting in the correct output.

As you can see, the 'mteval' modifier lets the output of a tag be interpreted as more Movable Type template code, and this is quite powerful.  The trick is getting some tag to output valid Movable Type template code.  Tags put inside in a <mt:setvarblock> tag will get interpreted themselves, that is why I used the trick with the 'foobar'.  If I hadn't done this, Movable Type would have tried to evaluate the half-formed tag "<mt:entrydatamy_field_<mt:var name="__index__">" which would have resulted in an error message...

No TrackBacks

TrackBack URL: http://www.movabletips.com/cgi-bin/mt/mt-tb.cgi/32

Leave a comment


Movable Type Help?

"Can my Movable Type issue or project be taken care of by a professional?" Yes It Can Be! Contact YesItCan.be

Tags

Powered by Movable Type 5.2.7