Method to override (or add to) styles for a particular news entry

There have been several times where I wanted to change a style for a particular element in a news article. Usually you want all articles to have the same look and feel, but if you need to for some reason for some one-off application, and don't want to use inline styles , then this is the trick for you.

One solution (which I did yesterday, which got me thinking) is to put a div around your content, set it to a class, and make a change to your news stylesheet to customize the elements in that div. However, it's a pain to have extra one-off styles in your stylesheet lying around, if you're never going to use them again.

In short, we will be creating an "overridestyle" field definition in News -> Field Definitions, editing the News Detail Template to capture this field, and editing the site template to include this info, if available. This technique is a slight modification of the method to put the news title in the page <title>

NOTE: This method will only work if $config['process_whole_template'] is false in config.php (default). This ensures that the body is processed before the head, so that variables set in {content} can be used in the <head>

Step 1: Create a new "Field Definition"

  • Go to News -> Field Definitions and click on "Add Field Definition"
  • Name: overridestyle
  • Type: Text Input (I tried text Area, but it gets WYSIWYGged, also Text Input is more unobtrusive, if not using it)
  • Max Length: 255 should be enough

Step 2: Update the News Detail Template. Go to your detail template and enter the following at the end:

{assign var='overridestyle' value=$entry->overridestyle}

This captures your 'overridestyle' field definition into a variable called $overridestyle

Step 3: Update Your Site Template. Edit your site template and place the following under your {cms_stylesheet} tag:

{if isset($overridestyle)}
<style type="text/css">
{$overridestyle}
</style>
{/if}

This will only put style info if you have it set in your news article.

That's it! Now edit a news article and put something like p {color: green;}  a {text-decoration: none;} in your overridestyle field and test it out!

This technique can be used with little or no modification for modules other than news, like CGBlog, CGCalendar, Products (and any other module that supports custom Field Definitions)

This solution isn't optimal if you have a site with many users, and you don't want your news staff editing menu CSS, etc.

Originally posted on the CMSMS Forum

Comments