Front-end engineer with a passion for learning something new every day

Theming a Views Post Date With Drupal 7 ("Date in Parts")

In my last blog post I showed how to theme a node post date to make it look more designed and themed. Essentially, this is taking your static date and breaking it up into parts, i.e. day, month, and year, each with its own seperate span tags. 

I'll take it one step further this time, and show how to do the same thing with a View. This assumes you are using the Views Module, and a use case would be if you want to display a feed of items with titles and teasers such as blog posts or news. You will be able to use the same styles as you did in the original post, so it's just a question of outputting the right information from Views. This involves a little rewriting of Views output, which is pretty straight forward. 

What's Needed / Steps

For this tutorial, it would be good to have a basic knowledge of Drupal Views, so you will need the Views Module as well as the Token Modules installed and enabled, and of course Drupal 7. See the resources section at the bottom for more information.

The first step is to create a basic View using Fields, and configure Title and a Teaser / Summary to display basic content. Once you have that, you will add in field: Content: Post date three times.  Set each date to display as Custom date format, and once again we can refer to the PHP date manual  to get the proper date formats in here. In my example I set the following:

  1. Custom date format: j, check the box, "exclude from display"
  2. Custom date format: M, check the box, "exclude from display"
  3. Custom date format Y, do not check the box, "exclude from display"

Custom Date format in the Views Settings for field: Content: Post date

## Where the Magic Happens

In the third field: Content: Post date field, expand the fieldset called "Rewrite results" and check the box, "Rewrite the output of this field." This is where all the magic happens, as we grab the first two fields and output them along with the third. The key here is to take a look at the "Replacement patterns" in the same dialog box which gives you the following "Tokens" for replacement:

  1. [created] == Content: Post date
  2. [created_1] == Content: Post date
  3. [created_2] == Content: Post date

It's important to note that replacement tokens are progressive, that is to say that you cannot do a rewrite replacement on a field with one that comes after it in the order of the fields, in this case the third field: Content: Post date, so that's why we choose to do the replacement on the third field, as then the previous two are available for replacement as tokens.

The third date field with all the rewrite info in the form of tokens

For a finished example of this, simply look at the blog feed from the home page and you will see a nice rounded corner box with the date for each post.



Read other blog posts