Actions

Difference between revisions of "More advanced Joomla! templates"

From Joomla! Documentation

(Remove 1.6 and 1.7 tags and add 3.x)
m (update transclusion call)
Line 1: Line 1:
 
{{version|1.5,2.5,3.1}}{{RightTOC}}
 
{{version|1.5,2.5,3.1}}{{RightTOC}}
==Which DocType header to use==
+
==DocType header to use==
{{:Which DocType header to use}}
+
{{:DocType header for templates}}
  
 
==Setting up page width==
 
==Setting up page width==

Revision as of 18:16, 23 June 2013

Contents

DocType header to use

Current thinking is that HTML5 should be used for Joomla! templates.

Recommended DocTypes

List of recommended DocTypes for different circumstances:-

  • HTML 4.01 Strict: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
  • HTML 4.01 Transitional: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  • HTML 4.01 Frameset: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">
  • XHTML 1.0 Strict: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  • XHTML 1.0 Transitional: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  • XHTML 1.0 Frameset: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
  • XHTML 1.1 DTD: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
  • HTML5: <!DOCTYPE html>

References about DocTypes

References about recommended DocTypes:


Setting up page width

Some templates provide the opportunity to select the type of page width, through its parameter settings. In case this does not meet the requirements, the template manager also allows the modification of the cascading style sheets. It is in those files, usually with the extension .css, that most, if not all, of the style (graphical) attributes are defined.

What is CSS?

CSS stands for Cascading Style Sheet. HTML tags specify the graphical flow of the elements, be it text, images or flash animations, on a webpage. CSS allows us to define the appearances of those html tags with their content, somewhere, so that other pages, if want be, may adhere to. This brings along consistency throughout a website. The cascading effect stipulates that the style of a tag (parent) may be inherited by other tags (children) inside it.

CSS Statements

The definition of an html tag is as follows:

tagname { attribute: value; attribute: value; }

Tagname may be any html tag but for the sake of setting up page width, what is of interest to us is an html tag that gives structure to a webpage. Some webpages are constructed from div tags while others are constructed on table tags. Usually, the tag has a 'width' attribute. You set up a page width by varying the value of the 'width' attribute.

Sometimes, html tags are not defined directly. They are given an id or a class name and CSS refers to those specific tags by their ids or their class names.

The definition of an id in CSS is as follows:

#idname { attribute: value; attribute: value; }

while the definition of a class in CSS is as follows:

.classname { attribute: value; attribute: value; }

Again setting up a page width means modifying the value of the 'width' attribute of any one of these definitions.

For example, the syntax could be by not including the parenthesis,

div {width:50%;}

This will make the width of the element to be 50% of its initial.

More information can be found from w3schools here

Value of the 'width' attribute

The value of the 'width' attribute may be in pixels or percentage. Pixels are fixed values; hence in this case, the width does not vary according to window resizing or changing screen resolutions. Percentage usually means that the width is a fraction of the width of its container. So if we have a screen resolution of 1024 pixels by 768 pixels and our page width is set to 80% of the browser window container, our page would be approximately 820 pixels (80% of 1024) provided that the window browser is open at its fullest.

About CSS page layouts

Professional websites separate styling from content. There are many reasons for this, the most obvious (to a developer) being the ability to control the appearance of many pages by changing one file. Styling information includes: fonts; backgrounds; images (that recur on every page); position and dimensions of elements on the page. Your HTML file will now be left with: header information; a series of elements; the text of your website. Because you are creating a Joomla! template, you will actually have: some header information; php code to request the rest of the header information; a series of elements; php code to request each module position; php code to request the main content.

Style information is coded in CSS, cascading style sheet, and usually stored in files with the suffix .css. A webpage contains a link to the associated .css file so a browser can find the appropriate style information to apply to the page. CSS can also be placed inside a html file between <style type="text/css"></style> tags.

All CSS code is applied to an element of the html/xml page. If you want a style to encompass a whole page, you would probably apply it to the <body> element. You can apply styles to any html element such as <p>, <table> or <div> elements. To style a particular element it needs to have an ID. For example, to apply styles to the <div> containing the title, you would first include an ID in the html - <div ID="title">.


Horizontal centering

Horizontal centering is achieved with CSS in one of two ways, depending on what you are centering.

For the first example, let's say you have a horizontal menu at the top of your page that you want centered in your layout. You would do it with a block of code in the linked CSS file like this:

#horz_menu {
   margin: auto; 
   width: 800px; 
   height: 25px; 
}

The "auto" value in the "margin" attribute centers the item, so this would create a menu area that is 800 pixels wide and 25 pixels tall and would be centered in whatever space it is placed in.

If you need to add some margin space above and below the menu and still keep it centered you would adjust the code like this:

#horz_menu { 
   margin: 20px auto 20px auto; 
   width: 800px; 
   height: 25px; 
}

This would add 20 pixles of space on the top and bottom of the menu while keeping the left and right margin in a centered mode.

The second example is when you simply want to center text, in which case you just add the "text-align" code.

#horz_menu a {
   padding: .75em 0 .52em 0; 
   font-size: 0.8em; 
   font-weight: bold; 
   color: #0033CC; 
   background-color: transparent; 
   text-align: center; 
}

This would cause any links within the horz_menu div tag of the html code to be centered in the horizontal menu. They would also have .75em of padding above and .52em of padding below them.

These same techniques work for the overall page layout as well. Let's say you want the shell content area of your page to be 900 pixels wide and to be centered on the page and that you want the headline to be centered within it. Your CSS code would look something like this:

#page_container {
   margin: auto; 
   width: 900px; 
   background-color: #FFFFFF; 
   border: 1pt solid #660000; 
}
#page_container h1 {
   margin: 50px 0 20px 0 ; 
   font-size: 1.25em; 
   font-weight: bold; 
   color: #0033CC; 
   background-color: transparent; 
   text-align: center; 
}

This would create a page that has a main content box centered in the browser window with a white background and a brown border.

Any text inside a h1 tag that is inside the page_container div tag in the html code of the page would also be centered inside that main content box.

Of course the example above is a simplified example for demonstration and you would have more structure involved (left column, right column, etc).

So as you can see, horizontal centering for structural items is achieved with the "margin" attribute whereas horizontal centering for text items is achieved using the "text-align" attribute.

PHP essentials

Many web designers and casual website owners are not conversant with the PHP language in which Joomla! is written and since Joomla! templates usually contain PHP statements it is necessary to understand at least a little of the language in order to be able to create or customize templates. This chunk will describe, in simple terms, how to use each aspect of PHP in the context of a Joomla! template. For example, a simple explanation of the PHP if-then-else syntax using extracts from a template for illustration.

The best resource to learn PHP is probably hands on experience and Joomla can provide that to you thanks to it's native PHP code. This can be overwhelming for people who have not programmed before. Though Joomla is easy enough to install with the help of the community and a little of your time you'll have people asking you to do their websites.

One place that has a nice short list if functions and examples is http://en.wikiversity.org/wiki/25_Essential_PHP_Functions which is good to get familiar with PHP. Though for an extensive function list, explanations, and examples go to http://www.php.net.

Once you have the basics of PHP you'll need to get the basics of the Joomla PHP syntax. Start by looking at some existing extensions and check out the code and also take a look at some these Tutorials about Joomla:

That will help you get familiar with some of the functions available within Joomla's system and what they do (using the API). Take particular care to understand the MVC (model view control) setup.

If however, you are absolutely new to PHP, following may help as very brief introduction to PHP.

PHP Introduction

PHP is a scripting language designed primarily for producing dynamic web pages. It is embedded into an HTML page with tags like <?php...?>. When a page is sent to the PHP engine, the PHP tags are translated into HTML, which can then be rendered by a browser. A database is needed during translation since the script may need to pull data from the database. So to create PHP pages, we require the PHP engine, a database (typically MySQL) and the webserver, which will coordinate these actions and forward the final HTML to the browser. These three components can be installed separately; however, we have packages like WAMP (for Windows), MAMP (for Mac) and LAMP (for Linux), for your convenience.

PHP Installation

The packages can be downloaded from WAMP. WAMP stands for Windows Apache MySQL PHP. The instructions can be followed as given in the site and is pretty straightforward. The installation can be done is any directory (say D:/wamp). Once installed, it can be started from the program->start->WampServer. This should give a small icon in the system tray using which the server can be started/stopped/restarted. It also gives links to all important files like php.ini and other configuration files. For Mac users MAMP can be found here. For the purpose of this tutorial XAMPP can also be used.

PHP Round-trip

Our primary objective here is to write a small PHP page and have it rendered by the Apache web server. WAMP renders a page by looking in the www folder of the WAMP Install Directory, hereafter referred to as WAMP_HOME. Fire up your primary text editor, create a page and name it, say, first.php, and save it to the WAMP_HOME/www/x/y folder (x and y are folders created to organize the scripts) and write the following in the script:

<html>
<head>
   <title>Basic PHP Page</title>
</head>
<body>
<?php
echo "My first php snippet";
?>
</body>
</html>

Save this file, point your browser to http://localhost/x/y/first.php, and you should be able to see the echo message.

The primary things to note here are:

1. It is strongly advised that all PHP codes begin with: "<?php" and end with a "?>" tag. 
2. To have a semicolon [;] after each PHP statement.
3. The directory where this script resides needs to be given in the URL. 

This completes our round-trip. Now, for the sake of learning, you can either keep including new elements in this file or you can create separate scripts and load them in the browser.

PHP Variable Declaration and Data Types

We need to hold data for any programming. Following are ways you can define variables in PHP:

  1. $variable_name = 0;

    Note: here we did not define the type of variable, whether integer or string, that the variable should hold. This is referred to as dynamic scoping.

  2. the variable names should start with an alphabet and can contain alphanumeric characters and "_"
  3. Defining constants -
     define ("NAME_OF_THE_CONSTANT" , $value);
    

Basic Operators

The general operators are explained below:

a.      +   e.g. 6 + 3, addition operator, answer is 9
b.      –   e.g. 6 - 3, subtraction operator, answer is 3
c.      /   e.g. 6 / 3, division operator, answer is 2
d.      *   e.g. 6 * 3, multiplication operator, answer is 18
e.      %   e.g. 6 % 3, modulus operator, answer is 0
f.      .   e.g. '6'.'3', concatenation operator, gives string '63'
g.      +=   e.g. $x += 6, adds 6
h.      -=   e.g. $x -= 6, subtracts 6
i.      /=   e.g. $x /= 6, divides by 6
j.      %=   e.g. $x %= 6, modulus by 6
k.      .=   e.g. $x .= '6', concats 6 to x
l.      <   e.g. $x < $y, evaluates to true if $x is < $y
m.      >   e.g. $x > $y, evaluates to true if $x is > $y
n.      ==  e.g. $x == $y, evaluates to true if $x is equal by value to $y
o.      !=  e.g. $x != $y, evaluates to true if $x is not equal to $y
p.      ===   e.g. $x === $y, evaluates to true if $x is and $y is identical i.e both of same type both value and reference
q.      >=  e.g. $x >= $y, evaluates to true if $x is >= $y
r.      <=  e.g. $x <= $y, evaluates to true if $x is <= $y
s.      &&  e.g. ($x == 2 && $y == 3) , evaluates to true if $x equals 2 and $y equals 3
t.      ||  e.g. ($x == 2 || $y == 3) , evaluates to true if either $x equals 2 or $y equals 3
u.      xor e.g. ($x == 2 xor $y == 3) , evaluates to true if either $x equals 2 or $y equals 3 but not both
v.      ++  e.g. $x++, increments $x
w.      –-  e.g. $x--, decrements $x

Defining Array Structures

Ways of declaring arrays
Suppose we want many variables. We could have declared the variables as shown above; however, that is not elegant. Suppose you want 100 variables; declaring arrays come to the rescue. Note that the index in PHP starts with 0.

$my_guitar_heroes = array ("Hendrix", "Shankar", "Gilmour", "to_name_a_few!");

Or

$my_guitar_heroes [] = "Hendrix";
$my_guitar_heroes [] = "Shankar";
$my_guitar_heroes [] = "Gilmour";
$my_guitar_heroes [] = "to_name_a_few!";

Here PHP automatically assigns the index.

Or

$my_guitar_heroes [0] = "Hendrix";
$my_guitar_heroes [10000] = "Mainak";

Here, I knew the first and the 10,001st element but that's me!

Or a combination of the above means

Or

// Set the elements at positions 1 through 9999 to the value, "to be decided".
$my_guitar_heroes  = array_fill( 1, 9999, "to be decided" );

Accessing the Arrays

print $my_guitar_heroes[2]; //Access the 3rd element

Or

// Access the last element (Note that the element positions are numbered zero to 
// [number of elements] minus one.)
$my_guitar_heroes[count($my_guitar_heroes)-1];

Or

// Access the last element using a function call.
end($my_guitar_heroes);

Iterating Over the Element of an Array

foreach ( $my_guitar_heroes as $temp) {
  print "$temp<br />";
}

Control Expressions

To execute a statement of a collection of statements over and over, we use Control Expressions. The general syntax of the control structures are as follows:

if statements

if( $x > 0) {   
 print("$x is positive");
}  else if( $x < 0 ) {  
 print("$x is negative");
} else {
 print("$x is 0");
}

for loop

for ( $x=1; $x<= 10; $x++ ) {
 print "$x<BR/>";
}

while loop

$x = 1
while ( $x <= 10 ) {
 print "$x<BR/>";
 $x++;
}

do while loop

$x = 1;
do {
 print "$x<BR/>";
 $x++;
}while($x <= 10);

Defining Functions

Code which is duplicated in many places is best placed in a function. The following are the ways of describing the function:

function name_of_the_function( $arguments, $size='default_values_if_any' ) {
  print "here goes in the code"; 
  return "this value is returned, return statement is optional";
}

The arguments are passed by value. If they are to be passed by reference, then an argument is prefixed by "&" as below:

function name_of_the_function( &$arguments, $size='default_values_if_any' ) {
  print "here goes in the code"; 
  return "this value is returned, return statement is optional";
}

The scope of a variable defined within a function is valid only within that function.

Calling a function

$x = add(5, 3);

Debugging

Basic printing options
A basic way to debug is to print the value of the variable. The following basic statements achieve that:

  • echo "if double quotes are used then dollar variables are resolved";
  • echo 'if single quote are used then dollar variables are not resolved';
  • print "another way to print";
  • nl2br("any new line characters like \n get automatically resolved to HTML line breaks");

Apart from these, the log files are very helpful and can be found in the WAMP_HOME/logs directory.

Handling Forms

Stop hand nuvola.svg.png
Warning!

Joomla! provides a safer and cleaner method of accessing request data and alternative ways for accessing the session. Using any of these arrays is not recommended.


PHP does not change any HTML structure, thus any syntax of HTML remains the same. The part that PHP plays is making any part dynamic for e.g., the action attribute of a form can be coded as action=<?php my_own_action(); ?> so that it is dynamically generated. The part where PHP kicks in is after the form is submitted, say to obtain the values of the form fields, set cookies, etc. For this, super global variables are used, which are always available to PHP code. Some of these are:

  1. $_GET - get the data from a GET request
  2. $_POST - get the data from a POST request
  3. $_REQUEST - get the request
  4. $_COOKIE - obtain the cookies from the browser
  5. $_SESSION - obtain the session

These are all arrays, and behave accordingly.


Adding images

Split-icon.png
Split Page into Specific Joomla! Versions - J2.5 and J3.1

It has been suggested that this article or section be split into specific version Namespaces. (Discuss). If version split is not obvious, please allow split request to remain for 1 week pending discussions. Proposed since 13 months ago.

  • Upload Using Media Manager

The simplest way to add images is to upload them from your computer using the Media Manager. First, of course, you have to download the image onto your computer and be able to find it. Then, from the Control Panel (back-end administrative interface) navigate to Content -> Media Manager.

On the left is a directory tree, with the root directory "Media". This corresponds to the default "images" directory, yoursite/joomla/images. Pick a subdirectory where you want the image located, or else do nothing to upload the image to the default images directory.

At the bottom of the page is a typical Upload box. Click "Browse" to locate the image on your computer, then "Upload" to upload the file to the server.

  • FTP

Of course, you can upload images to a server using any standard FTP client. You might find this handier for adding images to template directories; however, if you have FTP set up, you probably don't need an explanation of how to add an image. Also, many server administration panels such as Cpanel and Plesk have upload capabilities.

  • Extensions

There are several extensions, available from the Joomla extensions section, that handle image uploads.



Declaring module positions

The templateDetails.xml file contains all the installation and core information for a template. In order for Module positions to be available for selection in the Module Manager, the positions must be declared in the templateDetails.xml file of the template.

Module Elements in templateDetails.xml

In the file, the sub-element <positions> along with its sub-elements <position> define the locations available for each Module position supported by the template. Here is a brief list of the commonly used names for the various module positions and how they are declared.

<positions>
  <position>top</position>
  <position>left</position>
  <position>right</position>                
  <position>bottom</position>
  <position>banner</position>
  <position>syndicate</position>
  <position>footer</position>
  <position>user1</position>
  <position>user2</position>
  <position>user3</position>
  <position>user4</position>
  <position>debug</position>
</positions>

Although these are commonly used, it is up to the template developer to choose both a module position name and the accompanying display layout.

The addition of module positions, as displayed above, is implemented in between the <positions> and </positions> tags. In between those tags in the templateDetails.xml file, add the name of the module position in between a set of <position> and </position> tags.

You can add and define new Module positions and give them any name you like, but it is recommended that you support at least those shown in the example above. This is so that some level of consistency is maintained when switching Templates or using multiple Templates on a single site.

Use and Implementation

A Joomla! template displays a set of modules added to a specific position using the <jdoc:include /> statement shown below:

<jdoc:include type="modules" name="name of module position" style="xhtml" />

For further information about <jdoc:include /> code and how to use it, see jdoc statements.

See also

Finding module positions on any given page

To get a visual indication of all module positions used on a page you can follow this procedure:-

  • Joomla 2.5Joomla 3.1 In the administrative backend go to Extensions->Template Manager. Click on Options and set Preview Module Positions to enabled.
  • navigate to the page in your web browser.
  • click into the URL field in your browser.
  • look for any "parameters" at the end of the URL. These are separated from the main part of the URL by a question mark. For example, in the URL http://mydomain.com/index.php?id=17, the "id=17" is a parameter.
  • if there are no parameters, append "?tp=1" to the URL and press RETURN. For example, http://mydomain.com/index.php?tp=1.
  • if there are already parameters in the URL, append "&tp=1" to the URL and press RETURN. For example, http://mydomain.com/index.php?id=17&tp=1.
  • the module positions will be outlined in red.

Note that in some circumstances there may be module positions available that are not outlined in red. This can happen when a template defines those module positions as conditional on there being modules enabled in that position. If there are no modules enabled in that position then the template may adapt and the position will not be visible.


Changing the site favicon

Favicon.png

Changing your website's favicon is a relatively easy task.

  1. Create a 16x16 pixel image. You may use graphic software such as Photoshop, Gimp, Paint.net or Windows Paint. Alternatively, you can also use an online tool such as http://antifavicon.com/
  2. Convert to ico format using free online sites such as:
  3. The file you created in this way will have the extension .ico. Copy the file to the /joomla/templates/<your template> directory and name it favicon.ico.
  4. Open a browser. Do you see your new icon? If so, congratulations. If not, that doesn't necessarily mean you did anything wrong. Browsers are designed to minimize data traffic, so they don't refresh the favicon every time they show a page. Even refreshing the page (F5) won't help. So you need to refresh more thoroughly:
    • Mozilla / Firefox / Safari: hold down Shift while clicking Reload, or press Ctrl-Shift-R (Cmd-Shift-R on Apple Mac);
    • IE: hold Ctrl while clicking Refresh, or press Ctrl-F5;
    • Konqueror: simply click the Reload button, or press F5;
    • Opera users may need to completely clear their cache in Tools→Preferences.
    • Chrome: Shift-F5
    • If this doesn't work you will need to delete the temporary internet files and the history and then open your page again.

My favicon is in another location

Some templates contain code that redirects the browser to another directory or another icon file. To determine where your new favicon should be, examine http://yoursite.com/templates/your_template/index.php and look for code that contains the text <link rel="shortcut icon". There you will find the directory and the name of the icon file. Copy your icon to that place and give it the the name that link is pointing to (you might want to backup the old file). Make sure you set the security correctly such that you webserver has access to that file. Look at the example below.

<link rel="shortcut icon" href="http://yoursite.com/templates/your_template/icon/favicon.ico" />

If you don't want to just change the favicon.ico file in its respective template directory you can find the reference to the favicon.ico file in the html.php document. The path is "........\libraries\joomla\document\html\html.php". This should prevent the icon from toggling if you use

<link rel="shortcut icon" href="http://yoursite.com/templates/your_template/icon/youricon.ico" />

in the template html and you don't remove the favicon.ico file. (why call the icon twice?)

From the html.php

// Try to find a favicon by checking the template and root folder
                $path = $directory . DS;
                $dirs = array( $path, JPATH_BASE . DS );
                foreach ($dirs as $dir )
                {
                        $icon =   $dir . 'favicon.ico';
                        if (file_exists( $icon ))
                        {
                                $path = str_replace( JPATH_BASE . DS, '', $dir );
                                $path = str_replace( '\\', '/', $path );
                                $this->addFavicon( JURI::base(true).'/'.$path . 'favicon.ico' );
                                break;''