Drupal Style

Creating & Theming User Profiles In Drupal 7

Sep 14, 2011

On one of the recent sites that was being built by us I was introduced with a new challenge of theming user profile pages. Drupal provides a very elegant solution to accomplish this task. I will show you how it's done in this post.

The following instructions work with Drupal 7.x (it is similar to Drupal 6.x also, instructions here). First you will need create some user profile fields that will be shown to the public. To do so you must navigate to the following URL on your website: /admin/config/people/accounts/fields (you'll need correct permissions to get here if you aren't using an admin account).

Setting up the File

The first step is to create a file in your default theme directory that will handle this aspect of the theme. The file name must be named user-profile.tpl.php.

Handling Arrays

Within this file you are able to do any type of HTML structure as you wish. This template contains the following array that contains user data:

$user_profile: all user data is contained within this array, and is 100% ready for print

If need be, any of these arrays can be viewed using the php print_r function. Like so:

<?php print_r($user_profile); ?>

If you have the Devel module installed (any Drupal developer should have this) on your site, you should always use that to display your arrays as it's arranged in a much nicer fashion. Devel has a hidden function and can be used like so:

<?php dsm($user_profile); ?>

Note: Devel follows permissions and if you have insufficient permissions (or are not logged in), the function above will produce no output.

Sample Code

After you have the following arrays exposed you can proceed to creating your user template. You can do something like the following inside of your user-profile.tpl.php:

  <div id="user-profile">
      <?php print $user_profile['field_first_name'][0]['#markup'] .' '. 
                  $user_profile['field_last_name'][0]['#markup']; ?>
    <?php if (isset($user_profile['user_picture']['#markup'])): ?>
      <div id="user-picture">
        <?php print $user_profile['user_picture']['#markup']; ?>
    <?php endif; ?>

That's it! For more API information, you can check out Drupal's site here.