Spice up your Joomla and Mambo website with 2 great extensions!
Welcome, Guest. Please login or register.
Did you miss your activation email?

Login with username, password and session length

 
Advanced search

38736 Posts in 10488 Topics by 27226 Members
Latest Member: tbl
Pages: [1]   Go Down
  Print  
Author Topic: Applying PHP in Joomla! stylesheet  (Read 19317 times)
0 Members and 1 Guest are viewing this topic.
metacortex
Jr. Member
**
Offline Offline

Posts: 83


Designer


View Profile WWW
« on: December 06, 2007, 12:49:30 PM »

Applying PHP in Joomla! stylesheet

CSS is a web technology designed to control the presentation and design of the sites. Its existence returns to HTML its original purpose: managing the structure and flow of content.

CSS also opened up a range of possibilities to web designer, offering innovative and functional resources for the layout, in addition to the known reduction of all codes, which are also summarized in time savings, as well as greater ease in control labor.

However, it is possible to add more productivity CSS implementing dynamic language.The method is not new; the first examples that we saw dating back several years.This time its target implementation of the system Joomla!, An action that leads to many benefits and advantages, which we did not before.

The problem

Among the disadvantages of carrying the limit customization Joomla!there is the fact that often generate large stylesheets.This is due, in part, to the need to differentiate styles for the various areas of the site, such as content, weblinks, contacts, galleries, various modules, and so on.

The problem itself is not the size of the CSS, which usually does not weigh heavily. For example, to the stylesheet weight some 20Kb requires more than 1000 lines of code.

It is precisely in this amount kilometric lines is the problem!Those who work with Joomla!steadily, surely we have invented a system of procedures to not lose in that thicket of codes.To counter this, some designers split the files according to the CSS organization of work, then importing from a main stylesheet.

This way we will not confuse as much as if there were all in a single document.This action solves the problem… until it comes to disperse the selectors to avoid redundancy property, which is a real setback which shatters the order of the styles, especially if we are given to classify them alphabetically.

So What is the specific cause of this problem?The answer is simple: The static quality of the stylesheet.When the HTML contains all the burden of code, obviously CSS must compensate for the uneven playing field with more information, more data.A dynamic management styles of leveling the equation so surprising.And you will love the results.

The benefits

The level of benefits offered by a dynamic CSS, directly depends on the requirements of the project to develop.In the case of webs dynamic benefits are indisputable.We can summarize them as follows:

  • Reduction of redundant CSS and / or dispersal of selectors: Specially, this can be seen in the layout of webs dynamic, where it becomes necessary to assign styles to different sections of the site. One way to counter this is usual in the allocation of several selectors to the same set of styles, which breaks the order of their disposal, especially if they are classified alphabetically.

  • Extra resources for developer: All the benefits of PHP are available to be used creatively and achieve goals that would be impossible with a stylesheet common.

  • Equitable distribution of the burden of dynamic code: The fact of implement PHP in the stylesheet is summarized in simplifying many processes.Later we'll work on this issue in detail.

  • Clean browser interpretation of document: There are no bugs or strange surprises in the reading of a dynamic CSS by the browser.

  • It don't breaks W3C standars: If the stylesheet is well constructed, the validator will approve it normally.
Points against

So far we have seen a couple of minor glitches that do not affect the operation, but anyway we note them:

  • The CSS is included in the interpreted HTML: A separate CSS can process the majority of PHP code.However, there is a problem with the specific functions of Joomla!, which are not run if the style sheet is linked as a standard CSS.

  • Only works if you add the file as an include:This causes the content will be reflected directly in HTML, running to perfection, but it is possible that some find this somewhat ugly.

  • The CSS information is reloaded each time you change the page: A few grams more throughout Kb load.Some designers addicts to reducing weight in the set of files will experience some discomfort with this.
As for the work of CPU processing PHP information contained in the style sheet dynamics, we do not believe it represents an inconvenience.The load of instructions for the CSS will not be as relevant as to delay the time of server processing.

Recall also that the intention is not to add more code to our project, but reduce it in a synergistic manner to achieve better results thanks to its logical and equitable distribution.

The current method of work in Joomla!

Then explain part of the professional method of customizing a site Joomla!.Suppose we want to put a logo on our homepage and the other in the rest of the site.

In index.php:
Code:
if ($option == 'com_frontpage') {
  <div id="cabezal"></div>
  } else {
  <div id="cabezal-2"></div>
}
… And in CSS:
Code:
div#cabezal {
   background: url(imagen-1.jpg) no-repeat;
   width: 400px;
   height: 200px;
}

div#cabezal-2 {
   background: url(imagen-2.jpg) no-repeat;
   width: 400px;
   height: 200px;
}
But if do not want a repetition of styles, this is what you do:
Code:
div#cabezal, div#cabezal-2 {
   width: 400px;
   height: 200px;
}

div#cabezal {
   background: url(imagen-1.jpg) no-repeat;
}

div#cabezal-2 {
   background: url(imagen-2.jpg) no-repeat;
}
This example illustrates a minimum allocation of different classes to a single section.Imagine the mess of styles that would occur if we want to further customize modules, typography and the entire presentation between one and another area in the site.

Some we "save" a stretch of work changing the name of the parent class of layer that operates as container, and instead of writing -for example- div#cabezal-2, we place it as a #contenedor-2 div#cabezal; in this way, everything that affects this section shall be governed by #contenedor-2 [class].If there is a parent layer, all the labels contained within it will lead its class early.

Other way of customizing classes offered Joomla!in native form, through the possibility of adding a suffix to the class of a given module, component, and even menu article via admin panel.The change would be archived in the database.

Whether one way or another, the inevitable result is 1) the accumulation of styles and 2) the difficulty in locating and management styles from a certain level of the work.It is not a condition exclusive of Joomla! but any web application, but given its breadth of functions and resources (and therefore of styles), in Joomla!becomes more visible.

We already mentioned that the problem is the quality static CSS.The solution was always before our eyes and is as follows:
« Last Edit: December 06, 2007, 01:31:31 PM by metacortex » Logged

"If you fall down seven times, get up eight."

JoomlaWorks Support Team
metacortex
Jr. Member
**
Offline Offline

Posts: 83


Designer


View Profile WWW
« Reply #1 on: December 06, 2007, 12:49:59 PM »

Building a dynamic CSS oriented to Joomla!

The method we are about to learn is a dramatic turnaround to the way in which we see currently designing sites Joomla!.It is possible that another type of dynamic platform does not require much sophistication in management styles.In Joomla!, however, we need a channel capable of shortening steps to follow when dealing with designing a website.La primera vez que observé este procedimiento fue en la hoja de estilos del pack PhpMyAdmin; luego de recoger mi mandíbula del suelo pude comprobar que efectivamente no es una novedad, sino -para nuestra fortuna- un método bien practicado y documentado en la web a nivel general, aunque lamentablemente escaso en nuestro idioma. The first time I noticed this was in the stylesheet of PhpMyAdmin's pack; when I pick up my jaw from the ground I saw that indeed is not a novelty, but -to our good fortune- a method practiced and documented on the web at overall.

The preparation of the files is one of the most important steps.The first thing we will do will be to define the routes in the index.php of our template.We'll do this through variables, which not only will assist our CSS dynamic function properly, but to shorten many procedures of the design process.In addition, we'll "tell" to the index where are the styles:

Code:
<?php
$nombre_plantilla 
'mi_plantilla'// El nombre de nuestra plantilla
$ruta $mosConfig_live_site.'/templates/'.$nombre_plantilla// La ubicación de la plantilla
$rutacss $mosConfig_live_site.'/templates/'.$nombre_plantilla.'/css/'// La ruta de las hojas de estilo CSS
$rutaimg $mosConfig_live_site.'/templates/'.$nombre_plantilla.'/images/'// La ubicación de las imágenes requeridas por la hoja CSS
$ruta_absoluta $mosConfig_absolute_path.'/templates/'.$nombre_plantilla// La ruta absoluta de la plantilla
include_once($rutacss .'/css.php'); // Inclusión de la hoja de estilos
?>

As you noted, the stylesheet is being called as a common PHP file. Again, it is certainly possible to link it as a separate CSS, but such action disables the most important functions of Joomla!and in that case it would be worthwhile to implement it.

As for the action to define paths, has good reason: Being a CSS included in HTML, routes images no longer aim from the index of the template, but from the root directory index.php site.The variables save us the trouble of writing such long addresses all the time.

Now we will focus on creating a file called css.php (or as desired) in the location that is most convenient to us.In this case we put it in the directory of stylesheets /templates/my_template/css/css.php. Now we introduce the first data:
Code:
<style type="text/css">
   <?php 

$css
='

//Here go the styles

'
;

$css str_replace('url(' 'url(' .$rutaimg $css); // images path
$css str_replace('@import url(' '@import url('$rutacss $css); // path of imported CSS
echo $css// CSS output
?>

</style>
Already you are checking the importance of defining paths? The penultimate line aims to address properly the folder where the pictures, through a replacement function.Moreover, the last line is the one that will output to everything placed in the space for the styles.

Our dynamic CSS is ready to receive data. Let us now some practical examples.

Example 1: Suppose you want to put a logo on our homepage and other in the rest of the site.(To help understand the syntax comments, we have been placed to the right of each line).
Code:
<style type="text/css">
<?php

  
if ($option == 'com_frontpage') { // "If we are in homepage" 
    
$logo 'url(logo-portada.jpg) #ffffff no-repeat;'// "this will be the result"
    
} else { // "else..."
    
$logo 'url(logo-generico.jpg) #ffffff no-repeat;'// "... the result will be this"
  
}

$css '

div#cabezal {
  background: '
$logo .'; // Applying instructions through variables
}

'
;
$css str_replace('url(' 'url(' .$rutaimg $css);
echo 
$css;
?>

</style>
Surely already begin to visualize the savings in time and effort.Only this action averted:

  • To do the job of differentiating components in index.php, only to assign different classes, and consequently…
  • ... the redundance of classes in CSS, or…
  • ... that we assigning suffixes different classes level panel, unnecessarily, which would lead to more redundancy or-at best dispersion selectors to try to reduce repetition.
Meanwhile, the result of the above example is simple to check.Looking at your stylesheet from the browser, only there will be a div#cabezal, but with consistent data to the section in which we find ourselves at that time.Let us continue with more examples.

Example 2: Now let's say we want to put a logo differently on the Weblinks section while maintaining the above.
Code:
<style type="text/css">
<?php

if ($option == 'com_frontpage') { // "If we're in homepage" 
   
$logo 'url(logo-portada.jpg) #ffffff no-repeat;'// "this will be the result"
   
} else if ($option == 'com_weblinks') { // "but if we're in weblinks section..."
   
$logo 'url(logo-enlaces.jpg) #ffffff no-repeat;'// "... result will be this"
   
}else{ // "else..."
   
$logo 'url(logo-generico.jpg) #ffffff no-repeat;'// "... this will be the result"
}
$css '

div#cabezal {
  background: ' 
.$logo '; // This remains without change
}

'
;
$css str_replace('url(' 'url(' .$rutaimg $css);
echo 
$css;
?>

</style>
Logged

"If you fall down seven times, get up eight."

JoomlaWorks Support Team
metacortex
Jr. Member
**
Offline Offline

Posts: 83


Designer


View Profile WWW
« Reply #2 on: December 06, 2007, 12:50:44 PM »

Example 3: Now consider another variant of the case a little more complex.Suppose that the same logo of the Weblinks is smaller than the others.
Code:
<style type="text/css">
<?php
  
// Same code as above, as a reference
  
if ($option == 'com_frontpage') { 
    
$logo 'url(logo-portada.jpg) #ffffff no-repeat;'
    } else if (
$option == 'com_weblinks') { 
    
$logo 'url(logo-enlaces.jpg) #ffffff no-repeat;'
    }else{ 
// "De lo contrario..."
    
$logo 'url(logo-generico.jpg) #ffffff no-repeat;'
  }

//Here we start with size configuration of logos

  
if ($option == 'com_weblinks') { // "Si estamos en los Enlaces Web"
    
$logo_ancho '400px'// "Éste será el ancho del logo"
    
$logo_alto '200px'// "y éste el alto"
    
}else{ // "De lo contrario..."
    
$logo_ancho '300px'// "Éste será el ancho del logo"
    
$logo_alto '150px'// "y éste el alto"
  
}

$css '

div#cabezal {
  background: '
$logo .';
  width: '
$logo_ancho .';
  height: '
$logo_alto .';
}

'
;
$css str_replace('url(' 'url(' .$rutaimg $css);
echo 
$css;
?>

</style>

Dynamic semantic?

There is now a factor that should be taken in mind and internalize as a principle.In the modern web design there is a very simple and foolproof rule: HTML is responsible for all matters relating to the structure and CSS for everything related to the presentation.

Since the CSS also became a dynamic, this rule should remain in force: PHP code that controls the structure will be written into the HTML, and PHP which controls the presentation will be written into the CSS style sheet.

This not only sounds logical, but it will help us to better organize our work, both in the location/provision of the code as in problem solving, as well as making it easier to search for and identification of potential problems (ranging from simple layer poorly placed, to errors of various kinds).

Building a dynamic web is a complicated process itself, because the site is not composed of files, all information, links, sections, and other categories based as text in a database.If you want to customize a website up in these conditions, it is necessary to find a more synergistic and organized use to the engine that controls the dynamic stuff, PHP.

Just imagine the possibilities of what you can achieve.For a sample of what we mentioned, see the following example:

Example 4: Here we are going to rotate 3 images of a header in random order.The rotation would occur with each page refresh, while preserving the same class all the time.All this using only dynamic CSS:
Code:
<style type="text/css">
<?php 

  $imagenes 
= array("imagen1.jpg","imagen2.jpg","imagen3.jpg");
  
$resultado $imagenes[rand(0count($imagenes)-1)];

$css '

div#cabezal {
  background: url('
$resultado .') no-repeat;
}

'
;
$css str_replace('url(' 'url(' .$rutaimg $css);
echo 
$css;
?>

</style>
Example 5: Now lets add more seasoning at the same event.Suppose that when the Homepage show a set of rotating logos, the Content section show anotherset, while Weblinks section will have a different one:
Code:
<style type="text/css">
<?php 

  
if ($option == 'com_frontpage') {
     
$imagenes = array("imagen1.jpg","imagen2.jpg","imagen3.jpg");
     } elseif (
$option == 'com_content') {
     
$imagenes = array("imagen4.jpg","imagen5.jpg","imagen6.jpg");
     } elseif (
$option == 'com_weblinks') {
     
$imagenes = array("imagen7.jpg","imagen8.jpg","imagen9.jpg");
  }

  
$resultado $imagenes[rand(0count($imagenes)-1)];

$css ='

/* Of course, CSS part remains without change */

div#cabezal {
  background: url('
$resultado .') no-repeat;
}

'
;
$css str_replace('url(' 'url(' .$rutaimg $css);
echo 
$css;
?>

</style>
It is perfectly possible to do this work in the dynamic HTML and adding a few more styles.The above procedure only reflects a style in the results of CSS, which changes depending on the section where the user.It is very important to allocate portions of the code in the correct file, and distribute the pieces in a logical way.

Previously it was mentioned that the work could be better organized following the same principle that governs the semantic web design: Structure for HTML and CSS for presentation.Certainly it is possible to do more with dynamic CSS, but after a few test scenarios that force capability and original purpose of CSS, I could see that it is better to keep things within this principle, otherwise they will cause more problems those resolve.

Therefore it is better to spread the load, because one of the main reward is the fact to liberate much of the responsibility to HTML part (index.php of our template).Previously it was necessary to create new classes, leaving the entire burden dynamic to HTML, while the CSS remained static and accumulating eternal lines to compensate for the uneven playing field.

Conclusion

So far we have seen to PHP doing more productive work that a mosLoadModules or other proper syntax of a common template.Carrying styles management to a dynamic character, we have made significant simplification of several aspects which have so far proved a headache.The PHP + CSS combination implies the existence of a wealth of resources, so long as to consider a large and unexpected door open with a lot to build on.

The semantics of the code also contributes -though not itself- to synergistically enhance the quality of the project.In the field we work, synergy is to achieve better results with the lowest possible use of resources.Using it with skill and creativity, surely find more rapid and simplified ways to achieve the same goals that previously required a few extra steps.

As a Web designer it is necessary to have clear what level of coverage you need from your resources and prepare for new skills, which determines the difficulty the same goals that you propose to complete.The explained method is not astronautical science or nuclear engineering.

All that is required is our willingness to acknowledge that there is an ingredient rather than pure HTML and CSS, which will help us to develop sites more impressive, with high levels of personalization and comprehensive quality. Is that now you find it difficult not to want to try?.
Logged

"If you fall down seven times, get up eight."

JoomlaWorks Support Team
Pages: [1]   Go Up
  Print  
 
Jump to: