• vBulletin Template ForEach

    aaaThe other day whilst coding the online user map for this site I needed to use a foreach loop within one of the vBulletin templates to access data within an array, In earlier versions of vBulletin this wasn't possible as the foreach didn't exist.

    There seems to be a distinct lack of documentation on what is and isn't supported in the latest 4.0.x version of vBulletin and I didn't even know the following existed until a vBulletin support member explained it to me, I thought I'd make it easier for anyone else programming in vBulletin and write a quick tutorial on how to use it.

    HTML Code:
    <vb:each from="array" key="key" value="value"></vb:each>
    You could use the above to browse through and get information from an array such as this below:

    PHP Code:
    // We have an array of users available in PHP. 
    // It looks like this: 
    // $users = array( 
    //    1 => array('username' => 'Adam', 'email' => 'adam@adam.com'), 
    //    2 => array('username' => 'Ben', 'email' => 'ben@ben.com'), 
    //    3 => array('username' => 'Chris', 'email' => 'chris@chris.com') 
    // ); 
    HTML Code:
    <!-- our template code... -->
    <vb:each from="users" key="userid" value="userinfo">
    	<li><a href="member.php?u={vb:var userid}">{vb:var userinfo.username}</a></li>
    </vb:each>
    HTML Code:
    <!-- will output... -->
    	<li><a href="member.php?u=1">Adam</a></li>
    	<li><a href="member.php?u=2">Ben</a></li>
    	<li><a href="member.php?u=3">Chris</a></li>
    Note that you can also access variables by their id value instead of a keyword:

    HTML Code:
    <vb:each from="users" key="userid" value="userinfo">
    	<li><a href="member.php?u={vb:var userid}">{vb:var userinfo.0}</a></li>
    </vb:each>
    I hope this helps anyone that like me didn't realise the foreach statement was now functional in vBulletion 4.
  • Stay Updated