Difference between revisions of "Advanced topics"

From Joomla! Documentation

m (Tutorial:Advanced topics moved to Advanced topics: Moved page to main namespace because the Tutorial namespace is deprecated)
(No difference)

Revision as of 10:39, 14 January 2011

<translate> Templates are executed in a two-phase process that makes full use of the PHP parser to provide considerable flexibility and performance to the template designer. Templates are executed in the context of the document object so that the $this object is always the instantiation of the JDocument class. </translate>

<translate> Before template execution begins, the component will have been executed and its output buffered for later use. </translate>

<translate> Template execution then proceeds as follows: </translate> <translate>

  • Template parameters (if any) are loaded.
  • Template language (if any) is loaded.
  • If legacy mode is on, the configuration variables are copied as globals.</translate>

<translate>

  • The template file (index.php) is loaded and executed (by PHP). The output is buffered. This is phase 1 of the two-phase process. Everything between <?php and ?> tags is executed as PHP code. Everything outside of these tags is output but otherwise ignored. As the output is being buffered, nothing is sent to the client web browser at this stage.</translate>

<translate>

  • A favicon.ico file is looked for, first in the Joomla! root directory, then in the template root directory. The latter will override the former if found.</translate>

<translate>

  • The output that was buffered in phase 1 is now parsed for <jdoc:include> elements. This is phase 2 of the process. For each jdoc element found, the appropriate renderer class is loaded and its render method is called. The output from the render method replaces the <jdoc:include> element itself in the output buffer. In the case of module renderer classes, this triggers the execution of the modules and the buffering of their output.</translate>

<translate>

  • Certain template-specific HTTP headers are added to the list of headers to be output.</translate>

<translate>

  • Control is then passed back to the JApplication object which will handle the rest of the process of getting the now-rendered web page back to the client web browser.</translate>



<translate>

Error Page Templates[edit]

By default Joomla! uses special templates when it needs to raise an error response. These are located in the templates/system directory. For server-level status codes these are named for the status code that is being raised. The default system error pages are: </translate>

  • templates/system/403.php (Status code: 403 Forbidden)
  • templates/system/404.php (Status code: 404 Not Found)
  • templates/system/500.php (Status code: 500 Internal Server Error)

<translate> In addition, these system error pages are also available:

  • templates/system/component.php (not sure when this is used)
  • templates/system/offline.php is used to render the "site is offline" message.

</translate>

<translate> Note that jdoc:include elements are not parsed in these error pages.

The status codes are defined as part of the HTTP protocol in RFC2616. For further information on HTTP status codes see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html </translate>

<translate>

Styling the Error Pages[edit]

These pages can be styled using the following CSS classes:

  • errorboxheader
  • errorboxbody
  • techinfo

</translate>



<translate> Joomla! uses the templates/system/error.php file to handle several HTTP Status errors, including "403 Forbidden", "404 Not Found", and "500 Internal Server" errors. You can style the error results, if desired. </translate>

<translate> It is important to understand that error.php is an independent file from the Joomla! CMS but dependent on the Joomla! Platform. Plugins do not run on the file. You cannot include modules or use <jdoc:include> statements. </translate>

<translate>

Overriding the System Error Results[edit]

To override the system error results, copy the templates/system/error.php file into your templates/<template-name> directory. </translate>

<translate> If it finds one, Joomla! will use the error.php file from the current template, in place of the system file. </translate>

<translate> You can format the page, as desired, to match your template.</translate>

<translate>

Overriding the System Styling[edit]

If you want to change the styling, copy the templates/system/css/error.css file into your templates/<template-name>/css directory. </translate> <translate> Next, update your templates/<template-name>/error.php file to reference the new location of the stylesheet by changing this line, accordingly: </translate>

<link rel="stylesheet" href="<?php echo $this->baseurl; ?>/templates/system/css/error.css" type="text/css" />

<translate> Then, simply change the error.css, as desired, for your styling requirements.</translate>

<translate>

Customizing Error Messages[edit]

You can add conditional logic to vary the message returned, dependent upon the specific error code. </translate>

<translate> Here is an example of how to trap a 404 error and provide a custom message. </translate>

<?php  if ($this->error->getCode() == '404') { ?>
	<div id="errorboxheader">Page not found</div>
		<div id="errorboxbody"><p>Sorry! That page cannot be found.</p>
		</div>
	</div>
<?php } ?>

<translate>

HTTP Status Code[edit]

When a request is made for a page on your site, the server returns an HTTP status code in response to the request. Joomla! returns a '200 - the server successfully returned the page' for error pages. This is problematic for those working with Google Webmaster Services and trying to get a sitemap resolved. </translate>

<translate> If you want Joomla! to return a status code for the error, you can do so by adding logic before the DOCTYPE line, as follows: </translate>

<?php 
if ($this->error->getCode() == '404') {
	header("HTTP/1.0 404 Not Found");
} ?>

<translate>

More HTTP Status Code Information[edit]

</translate>

<translate>

</translate>

<translate>

Using Theme Header and Footer on Standard Error Page[edit]

</translate> Joomla 1.5 <translate> If you want to see the error page in theme design and don't like redirecting to error page URL or duplicating HTML in the error page template, here is a way to apply your theme template to the error page. </translate>

<translate> First, put the following code in templates/<template-name>/error.php: </translate>

<?php
// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );

include dirname(__FILE__) . "/index.php";
?>

<translate> Then make the following edits to templates/<template-name>/index.php: </translate>

<translate> 1. Find the following code in index.php </translate>

<jdoc:include type="head" />

<translate> and replace it with the following </translate>

<?php if (!$this->error->getCode()) : ?>
<jdoc:include type="head" />
<?php else : ?> 
<title><?php echo $this->error->getCode() ?> - <?php echo $this->title; ?></title>
<?php endif; ?>

<translate> 2. Find the following code in index.php </translate>

<jdoc:include type="component" />

<translate> and replace it with the following </translate>

<?php if ($this->error->getCode()) : /* check if we are on error page, if yes - display error message */ ?>
  <p><strong><?php echo $this->error->getCode() ?> - <?php echo $this->error->message ?></strong></p>
  <p><strong><?php echo JText::_('JERROR_LAYOUT_NOT_ABLE_TO_VISIT'); ?></strong></p>
  <ol>
    <li><?php echo JText::_('JERROR_LAYOUT_AN_OUT_OF_DATE_BOOKMARK_FAVOURITE'); ?></li>
    <li><?php echo JText::_('JERROR_LAYOUT_SEARCH_ENGINE_OUT_OF_DATE_LISTING'); ?></li>
    <li><?php echo JText::_('JERROR_LAYOUT_MIS_TYPED_ADDRESS'); ?></li>
    <li><?php echo JText::_('JERROR_LAYOUT_YOU_HAVE_NO_ACCESS_TO_THIS_PAGE'); ?></li>
    <li><?php echo JText::_('JERROR_LAYOUT_REQUESTED_RESOURCE_WAS_NOT_FOUND'); ?></li>
    <li><?php echo JText::_('JERROR_LAYOUT_ERROR_HAS_OCCURRED_WHILE_PROCESSING_YOUR_REQUEST'); ?></li>
  </ol>
  <p><strong><?php echo JText::_('JERROR_LAYOUT_PLEASE_TRY_ONE_OF_THE_FOLLOWING_PAGES'); ?></strong></p>

  <ul>
  <li><a href="<?php echo $this->baseurl; ?>/index.php" title="<?php echo JText::_('JERROR_LAYOUT_GO_TO_THE_HOME_PAGE'); ?>"><?php echo JText::_('JERROR_LAYOUT_HOME_PAGE'); ?></a></li>
  </ul>

  <p><?php echo JText::_('JERROR_LAYOUT_PLEASE_CONTACT_THE_SYSTEM_ADMINISTRATOR'); ?>.</p>
<?php else : ?>
  <jdoc:include type="component" />
<?php endif; ?>

<translate> Now your theme template is applied to error pages too. </translate>

<translate> Note: Module includes in template will not work on error page created by this method (but will work on other pages). </translate>

<translate>

Using modules in error pages[edit]

</translate> <translate> Modules cannot be included in error pages in the same way as the template's index.php because you cannot use <jdoc:include> statements. There is an alternative way using JModuleHelper.</translate>

<translate> To include a single module by title, you can use:</translate>

if (JModuleHelper::getModule('menu')) { 
    echo $doc->getBuffer('module', 'menu');
}

<translate> To include multiple modules by position, you can use:</translate>

$modules = JModuleHelper::getModules( 'footer_3' );
$attribs['style'] = 'xhtml';
foreach ($modules AS $module ) {
    echo JModuleHelper::renderModule( $module, $attribs );
}



Note that a more up-to-date Joomla document covering this topic can be found at Adding JavaScript and CSS to the page, although it currently doesn't cover the more advanced topics at the bottom of this page.

<translate> JavaScript (also known as ECMAScript) is a scripting language primarily used in client-side web site development to extend and enhance an end-user's experience. Joomla provides developers with easy-to-use mechanisms to include JavaScript in their extensions using existing API methods. </translate> <translate> There are a number of methods for including JavaScript in your Joomla extensions; some of these are described below. </translate>

<translate>==Usage== </translate>

<translate> There are three methods for embedding JavaScript into your code using the Joomla API; JDocument::addScriptDeclaration, JDocument::addScript and script. These methods should be called either in your component's View class <yourcomponent>/views/<yourview>/view.html.php or template script <yourcomponent>/views/<yourview>/tmpl/<yourtemplate>.php or in the case of a module, in its template script <yourmodule>/tmpl/<yourtemplate>.php. </translate>

<translate>===Inline JavaScript=== </translate>

<translate> Blocks of JavaScript code can be declared directly within a component or module's display template using the JDocument class' addScriptDeclaration method: </translate>

<?php
$document = JFactory::getDocument();
$document->addScriptDeclaration('
    window.event("domready", function() {
        alert("An inline JavaScript Declaration");
    });
');
?>

<translate>===External JavaScript=== </translate>

<translate> Alternatively, you may wish to separate your JavaScript into a separate file. Separating your JavaScript into an external file can make your template code easier to read especially if the JavaScript is lengthy or complex. </translate>

<translate> There are two ways to include a JavaScript file using the Joomla! API. The first involves using the JDocument class' addScript method: </translate>

<?php
$document = JFactory::getDocument();
$document->addScript('/media/system/js/sample.js');
?>

<translate> The second uses the JHTML class' script method:</translate>

<?php
// Add the path parameter if the path is different than 'media/system/js/'
JHTML::script('sample.js', 'templates/custom/js/');
?>

<translate> API has changed in 3.x, so the second parameter cannot be a string. If you really need to use this method, you must include the absolute link to your JavaScript file: </translate>

<?php
JHtml::script(Juri::base() . 'templates/custom/js/sample.js');
?>

You can use options in a third parameter. This example shows the options version and relative . The file example should be saved in the folder media/com_example/js/example.min.js. So you do NOT need to insert the js in the path you insert as second parameter.

<?php
JHtml::_('script', 'com_example/example.min.js', array('version' => 'auto', 'relative' => true));
?>

<translate>

Description[edit]

The Joomla API's JDocument::addScriptDeclaration, JDocument::addScript and script methods embed JavaScript into Joomla's index.php via the jdoc head tag: </translate>

<jdoc:include type="head"/>

<translate> Using the JDocument::addScript or script methods to embed JavaScript includes would result in the index.php rendering the following HTML: </translate>

<head>
...
<script type="text/javaScript" src="/media/system/js/sample.js"></script>
...
</head>

<translate> Calling the class method JDocument::addScriptDeclaration would render the following HTML: </translate>

<head>
...
<script type="text/javaScript">
window.addEvent("domready", function() {
    alert("Embedded block of JS here");
});
</script>
...
</head>

<translate> Using these methods is highly recommended as it clearly differentiates another scripting language (JavaScript) from the main PHP code, ensures all JavaScript is correctly embedded between the <head></head> tags and, in the case of JDocument::addScript and JHTML::script ensures that a JavaScript file is included only once (I.e. there is no .js file duplication). </translate>

<translate>== Using a JavaScript Framework == </translate>

<translate> A Javascript framework provides developers with generic functionality for handling various coding tasks in a familiar, consistent and platform-independent way. A framework enables the developer to forget about the intricacies of implementing a certain function in different web browsers and focus on the requirements of the software. </translate>

<translate> Two Javascript Frameworks are provided as part of Joomla 3.x; jQuery and Mootools. jQuery is a newly introduced framework which integrates with Joomla's new Bootstrap HTML framework; Mootools is Joomla's legacy Javascript library which is now superseded by jQuery and is included for backwards compatibility with 3rd party extensions. </translate>

<translate> In nearly all cases you should use a framework when developing Javascript in your extensions or templates and including one is very simple with Joomla's API. </translate>

<translate>

Joomla 3.x jQuery[edit]

Please see the guide on Javascript Frameworks in Joomla 3.x for information about including a framework in Joomla 3.x </translate>

<translate>

Joomla 1.5/2.5 Mootools[edit]

Unless you are maintaining Javascript code which leverages Mootools or you are developing an extension for Joomla 2.5 or earlier it is recommended you use jQuery instead. </translate>

<translate> Firstly, you will need to include the Mootools code in your extension. To include the Mootools framework in your extension, you add the following code to your view.html.php or tmpl file: </translate>

<translate> FOR JOOMLA 1.5</translate>

JHTML::_('behavior.mootools');

<translate> FOR JOOMLA 2.5</translate>

JHtml::_('behavior.framework');

<translate> The above code results in the same outcome as the similar jQuery framework statement; that is it ensures Mootools is included correctly and only once. </translate>

<translate> Then using Mootools is almost identical to jQuery:</translate>

JFactory::getDocument()->addScriptDeclaration('
window.addEvent("domready", function() {
    alert($("list").getElements("li").length);
});
');

<translate> More information about Mootools is available at http://mootools.net/. For API documentation, visit http://mootools.net/docs/core. </translate>

<translate>== Important notes for 3rd party developers == </translate>

<translate> If you are creating a custom template override or extension that needs to add a custom JS file, make sure to add important dependencies such as Jquery or Mootools before your custom JS files. JS framework files must always be loaded before any other files to make sure they get executed first, otherwise other files that load before the frameworks they need are likely to end in JS exceptions. </translate>

<translate> Some templates like Protostar or Beez insert all the dependencies you need using functions like</translate>

JHtml::_('bootstrap.framework');

<translate> to load Jquery + Bootstrap, but you should not rely in this fact on your extensions or custom templates overrides. Always make sure your extension or custom override load the dependencies you need before the template does it, I will explain why later: </translate>

<translate> For example if you got a custom template override that needs to insert a JS file with some Jquery scripts that does fancy things on all the pages where that template override is being used. In that case you should declare this on the top section of that override file: </translate>

JHtml::_('jquery.framework');
$doc->addScript('templates/'.$this->template.'/js/fancy-script.js');

<translate> If you are developing a 3rd party extension that you plan to put on the Joomla! extension directory you should do something like this:</translate>

if($params->get('add_extension_resources', false))
{
    JHtml::_('jquery.framework');
    $doc->addScript('media/com_fancy/js/fancy-script.js');
}

<translate> The conditional clause to decide whether to add or not the extension resources is strongly encouraged and considered a good practice because it gives flexibility to 3rd party developers who don't want to use your extension resources and use custom/modified files without having to battle with Joomla! using workarounds and hacks to be able to remove your original extensions resources in order to avoid duplicates and conflicts. </translate>

<translate>

Explanation[edit]

If you check the source code of the index.php from the Protostar template, you can see that the statements </translate>

JHtml::_('bootstrap.framework');

<translate> is added way before the statement</translate>

<jdoc:include type="head" />

<translate> this can make you think that the framework files and your 3rd party files using methods like</translate>

$doc->addScript('templates/'.$this->template.'/js/fancy-script.js');
$doc->addScript('media/com_fancy/js/fancy-script.js');

<translate> will be added in the right order at the right spot, but that is not the case, because extension files and template override files are processed first and the index.php file of your current template is processed the last. This will cause that your custom JS files get inserted first and the framework files inserted from the template get inserted after. </translate>

<translate> This happens because the Joomla! API (such as $doc->addScript) uses an array to store the JS files paths and they get rendered in the document in the same order they where inserted into that array (FIFO stack). Also, once a file path is inserted on the array and another API call tries to insert the same file this action is ignored to avoid duplicates. It also means that the order of the files is not altered when the same files is attempted to be inserted several times. </translate>

<translate> Having said that doing this</translate>

JHtml::_('jquery.framework');
$doc->addScript('templates/'.$this->template.'/js/fancy-script.js');

<translate> at your custom templates overrides and extension, is required and does not cause harm or conflict with the call</translate>

JHtml::_('bootstrap.framework');

<translate> at your template index.php file.</translate>

<translate>== External Links == </translate>

Joomla 2.5 https://api.joomla.org/cms-2.5/classes/JHtmlBehavior.html#method_framework

Joomla 3.x https://api.joomla.org/cms-3/classes/JHtmlBehavior.html#method_framework

http://en.wikipedia.org/wiki/JavaScript

http://www.w3schools.com/js/default.asp

http://mootools.net/

http://jquery.com/



<translate> Web browsers sometimes differ in the way they render a page. For this reason you may wish to find out which particular browser a visitor is using in order to use some browser-specific CSS. </translate>

<translate> The following JavaScript defines a simple browser detection object that determines the browser's name and version by decoding the navigator.userAgent string. </translate>

function browserDetect()
{
  var browserNames=new Array("Opera", "MSIE","Netscape","Firefox");
  this.name="NK";
  this.mainVersion="NK";
  this.minorVersion="NK";
  
  for (var i=0; i< browserNames.length; i++)
  {
   var pattern='('+browserNames[i]+')'+'.([0-9]+)\.([0-9]+)';    
   var myRegExp=new RegExp(pattern);
   if (myRegExp.test(navigator.userAgent))
    {
      var results=myRegExp.exec(navigator.userAgent);
      this.name=results[1];
      this.mainVersion=results[2];
      this.minorVersion=results[3];
      break;
    }
  }
}

<translate> To use this in a script, you create an instance of this object: </translate>

var browser = new browserDetect();

<translate> The property browser.name will then give you the name of the browser (MSIE, Opera, Netscape or Firefox), browser.mainVersion will show the main version number and browser.minorVersion contains the minor version number. </translate>

<translate> This is not foolproof. It is much better to avoid writing browser-specific code. </translate>



Stop hand nuvola.svg.png
Warning!

This document is out of date! Do not use it. See https://developer.mozilla.org/en-US/docs/Web/CSS/@media

<translate> Using cascading style sheets (CSS), it is possible to use a set of directives (styles) depending upon the device being used to browse web pages. </translate>

<translate>===Media Types=== </translate> <translate> The recognised media types are:

  • all - Suitable for all devices.
  • aural - For speech synthesizers.
  • braille - Intended for braille tactile feedback devices.</translate>

<translate>

  • embossed - Intended for paged braille printers.
  • handheld - Intended for handheld devices.
  • print - Used for formatting printed pages.
  • projection - Intended for projected presentations, for example projectors or print to transparencies.
  • screen - Intended primarily for color computer screens.</translate>

<translate>

  • tty - Intended for media using a fixed-pitch character grid, such as teletypes, terminals, or portable devices with limited display capabilities. Authors should not use pixel units with the tty media type.
  • tv - Intended for television-type devices (low resolution, color, limited-scrollability screens, sound available).</translate>

<translate>===Examples=== You can assign a media type to a CSS declaration with the following syntax</translate>

@media print {
  body { 
    font-size: 12pt;
    font-color: #000000; 
  }
}

<translate> To assign more than one declaration style to more than one media type:</translate>

@media print, handheld{
  body { 
    font-size: 12pt;
    font-color: #000000;
  }
  img {
    max-width: 100%;
    height: auto;
  }
}

<translate> The directives can be used in the main CSS file or in a separate style sheet for a given media type. There must be an include to the CSS file in the templates <head> section:</translate>

<link rel="stylesheet" href="<?php echo $this->baseurl ?>/templates/beez/css/print.css" media="print" />

<translate> The recommended way to include a style sheet is:</translate>

<?php
$document = JFactory::getDocument();
 $tpath = $this->baseurl . '/templates/' . $this->template;
$document->addStyleSheet( $tpath . '/css/print.css', 'text/css', 'print'); // arguments: $path, $type, $media
?>

<translate> This way, you ensure the style sheet will be added to the document and is accessible to plugins (e.g for combining and compressing style sheets).</translate>


Enhancing template performance

Administrator (back-end) templates