Textpattern How To: Add Dynamic Body Classes to Your TXP Theme

Being able to dynamically generate and call data is one of the greatest things about building a site with a content management system. Why should the power of a CMS engine be limited to storing, retrieving and displaying content? Why not also use this engine to generate classes within your HTML that can also may your site’s design dynamic?

When I began working on designing a theme for Textpattern, I was heavily influenced by my previous work with the Sandbox WordPress theme. The dynamically generated semantic classes made things possible only using CSS that required editing the HTML/PHP template files before.

Inspired by a recent tutorial by Elliot Jay Stocks on how to add a dynamic body class or ID to WordPress themes and a comment made by Sam Brown, I thought I would share how a basic implementation of this can be added to Textpattern.

Making Textpattern add some Sandbox style

With the use of the TXP template tags and the built in conditional statements, I was able to add some basic dynamically generated classes to my site.

Just give me the code already

<body class="<txp:section /> <txp:if_individual_article> single id-<txp:article_id /> </txp:if_individual_article> <txp:if_category> category <txp:category /> </txp:if_category>">

Make sure the code does not contain any line breaks when adding to your theme. You can download the code snippet here: txp_dynamic_body_classes.txt (120) - 175 bytes.

What does that code do

While the simple code snippet doesn’t go to the extent of themes like Sandbox and K2, it adds some basic classes to the based on where you are in the site.

  • The home page simply generates:
  • A single post page makes: (Where id-225 is Textpattern’s ID# of the single post.)
  • The design category in the default section creates:
  • A post in the asides section creates
  • The about page generates:

Some examples

You could do some really geeky things like this:

Example in the usage of body classes 2

You could even make your own tumblelog.

Example in the usage of body classes 1

Hopefully, this will help someone out there…

5 Comments

  1. it seems useful.

  2. hey Thanks for share, :)

  3. Glad you guys liked it.

  4. Wow. Good idea. I mean, the concept is simple, but I never would have thought of doing it like that. Great tut.

  5. Thanks, Ben. I really missed Sandbox when I switched to TXP so this was a small attempt at incorporating some of its great features into this site.