ExpressionEngine CMS
Open, Free, Amazing

Thread

This is an archived forum and the content is probably no longer relevant, but is provided here for posterity.

The active forums are here.

Add a unique class to the body element on a per post basis...

May 15, 2010 11:53pm

Subscribe [3]
  • #1 / May 15, 2010 11:53pm

    Brad Dielman

    24 posts

    I have a client that requested the need to style certain blog posts uniquely based on the content of the current article. The style changes are very simple (background image or font change) so I figured adding a class to the body tag along with the post would be a good solution.

    I created a new custom field and add added it to the channel to allow them to add the text of the class to the post. I then wrapped the class attribute on the body tag in a conditional statement:

    {exp:weblog:entries weblog="blog" limit="1"}
    <body class="archive{if body_class !=""} {body_class}{/if}">
    {/exp:weblog:entries}

    This seems to do the trick, but I was wondering if there was a better way to handle this problem. Any suggestions anyone may have to improve on this is greatly appreciated.

    Thanks!

  • #2 / May 16, 2010 8:00am

    James Smith

    259 posts

    If the style changes are simple and unique to that page I’d probably add a dynamic <style> section in your <head>.

    If you prefer the body class approach, using the Single Field plugin you can avoid the heavy-duty machinery of the weblog:entries tag - http://ellislab.com/forums/viewthread/108494/

    A more complicated approach, but one which will shave a few extra DB queries from your page generation would be to use the incredibly versatile LG Replace plugin: grab the class value from inside your regular weblog:entries loop (the same place you generate the actual page content) and then move that value into the body tag with an LG Replace needle: http://ellislab.com/forums/viewthread/76788/

  • #3 / May 20, 2010 11:36pm

    Brad Dielman

    24 posts

    Thanks for the tip, James. I’ll look into those options.

  • #4 / May 21, 2010 11:52am

    Boyink!

    5011 posts

    Your approach is fine IMHO - not sure I’d add extra 3rd party code in this case.  I would suggest using the disable parameter on the weblog entries tag to speed performance.

    {exp:weblog:entries weblog="blog" limit="1" disable="trackbacks|categories|member_data|pagination"}
    <body class="archive{if body_class !=""} {body_class}{/if}">
    {/exp:weblog:entries}

    Also—if this is on a single entry page you could look at moving your main content weblog:entries open and close such that the <body> tag is between them - and then eliminate the tag pair specifically for this purpose.

.(JavaScript must be enabled to view this email address)

ExpressionEngine News!

#eecms, #events, #releases