Overwriting Joomla module or component views in the template

January 26th, 2009

Most of the Joomla modules and components have one or more templates that define how the content will be displayed by Joomla. These files are stored in the modules/mod_[module]/tmpl and components/com_[component]/views/[view]/tmpl folders and can be overwritten by the template.

Typical Joomla module has one view and this view is stored in file named default.php in the tmpl folder of the mode. Differently from modules, the standard components have several views, each for different component mode.

For example, the mod_poll module has one view that displays a list of poll options and buttons. The com_content component has several views: archive, article, category, frontpage, section.

Default views of the modules and components may be overwritten in the template by creating a file in specific location: the templates/[template]/html/com_[component]/[view]/ folder for the component and the templates/[template]/html/mod_[module]/ folder for the module. While rendering, Joomla looks into these folders for files that overwrite views and if a file with the same name exists, it uses it instead of the default view file.

The Beez template, shipped with Joomla, overwrites the templates of several components and modules so you can look through its html folder to get examples on how to customize component and module views for different modes.

Wordpress widgets internals – Part 1

November 20th, 2008

Wordpress widgets are the reusable information blocks that admin can place in one of the theme sidebars. The widget can display any information: RSS feed records, Twitter account events, Facebook board events, stock quotes, geography of visitors, polls, etc.

Technically, Wordpress widget is a PHP function that may perform a variety of steps to produce the HTML fragment that will be inserted to sidebar. Sidebar calls these widget functions in the order and with parameters defined in administration part of the Wordpress site.

For example, let’s open the sidebar.php of the default Wordpress theme and analyze its content:

<div id="sidebar">
    <ul>
    <?php /* Widgetized sidebar, if you have the plugin installed. */
        if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar() ) : ?>
        <li>
        <?php include (TEMPLATEPATH . '/searchform.php'); ?>
        </li>
        ...
        <?php endif; ?>
    </ul>
</div>

The first if checks for existence of the dynamic_sidebar function and calls it. This function prints the widgets and returns true when the sidebar contains widgets and false otherwise. If the sidebar does not contain the widgets the default sidebar content, the if statement body, is displayed.

The dynamic_sidebar function calls the wp_get_sidebars_widgets function and iterate over its result, the list of sidebar widgets, calling callback function of the widgets.

The following table shows the list of default Wordpress widgets and their callback functions:

Widget Callback function Description
Pages wp_widget_pages Your blog’s WordPress Pages
Calendar wp_widget_calendar A calendar of your blog’s posts
Archives wp_widget_archives A monthly archive of your blog’s posts
Links wp_widget_links Your blogroll
Meta wp_widget_meta Log in/out, admin, feed and WordPress links
Search wp_widget_search A search form for your blog
Recent Posts wp_widget_recent_entries The most recent posts on your blog
Tag Cloud wp_widget_tag_cloud Your most used tags in cloud format
Categories wp_widget_categories A list or dropdown of categories
Text wp_widget_text Arbitrary text or HTML
RSS wp_widget_rss Entries from any RSS or Atom feed
Recent Comments wp_widget_recent_comments The most recent comments

Information about available (or registered) widgets is stored in the $wp_registered_widgets global array variable and other functions query this variable to fetch the list of available widgets and get information about the widgets.

The widget can be registered with the wp_register_sidebar_widget function. This function calls the widgets_init action and modifies the $wp_registered_widgets array.

Here is the sample code fragments extracted from Wordpress that registers several widgets using the wp_register_sidebar_widget function:

The default Wordpress widgets are registered in the wp_widgets_init function. The following code fragment is extracted from this function:

$widget_ops = array('classname' => 'widget_pages', 'description' =>
    __( "Your blog's WordPress Pages") );
wp_register_sidebar_widget('pages', __('Pages'), 'wp_widget_pages', $widget_ops);
wp_register_widget_control('pages', __('Pages'), 'wp_widget_pages_control' );

$widget_ops = array('classname' => 'widget_calendar', 'description' =>
    __( "A calendar of your blog's posts") );
wp_register_sidebar_widget('calendar', __('Calendar'), 'wp_widget_calendar', $widget_ops);
wp_register_widget_control('calendar', __('Calendar'),
    'wp_widget_calendar_control' );

Joomla front page

October 27th, 2008

The front page of Joomla site contains of three major parts. The first depends on template and includes colors, styles, and position of elements. The second is the content, the menu items, and list of articles, login form, and other elements produced by Joomla modules. And the third is the content of a current displayed component.

 

Joomla front page: green - modules, red - content, other - template

Joomla front page: green - modules, red - content, other - template

 

 

Joomla modules are located in the modules folder of the Joomla installation and after installation this folder contains 20 modules for menu, search, login form, banners, etc. They can be configured in Administration section > Extensions > Module manager and each module can be added several times on the page.

An instance of the module has common options, such as position, order, access level, title, list of pages on which the module should be displayed, and custom module-specific options. Horizontal or vertical menu type option of the mod_mainmenu is an example of such option.

Each module may have one or more templates, these templates are saved in the tmpl folder in the module folder. For example, the mod_poll module template is loaded from the modules\mod_poll\tmpl\default.php file. Each module can implement own method for loading template, but most of them use the common way for this, which allows template developer to overwrite the template of the module.

Typical rendering:

$layout = JModuleHelper::getLayoutPath('mod_poll');
require ($layout);

Some of the components have several templates, like mod_newsflash which has horizontal and vertical layout variations.

Content of the component is included by the following line in the template:

 <jdoc:include type="component" />

When the page template is processed by the HTML document class, this line is replaced with the

JDocumentHTML::getBuffer(’component’) function call. getBuffer fetches the content saved by the following code fragment in application.php, line 125:

function dispatch($component) {
      ...
      $contents = JComponentHelper::renderComponent($component);
      $document->setBuffer( $contents, 'component');
}

The dispatch method is called by the following code fragment in index.php, line 68:

$option = JRequest::getCmd('option');
$mainframe->dispatch($option);

The $option variable contains string ‘com_content’ for the front page request.

So, when the ‘com_content’ string is passed to the JComponentHelper::renderComponent method, it loads the component options, includes main component file by constructing its name using the following pattern:

 components\com_{component_name}\{component_name}.php

The content of the main component file specifies how the component processes the request and which operations the component supports. The com_content component creates instance of the ContentController class, registers several actions and then executes the action.

The ContentController class is based on the JController classes, which is defined in the libraries\joomla\application\component\controller.php file. The ContentController only defines the methods unique to the content article, such as display, edit, save, vote, etc.

The display method of the com_content component sets the current view selector, frontpage or article, and calls display method of its parent class, JController. The JController::display method creates instance of the view, using the parameter specified by the ContentController::display method and executes its display method. The view is created by including corresponding file from the components\com_content\views folder. When the front page is displayed, the frontpage\view.html.php is included. This view includes templates from the frontpage\tmpl folder.

The frontpage com_component view can be configured in Administration section > Content > Front Page Manager. The layout of the front page can be configured in Administration section > Menus > Main Menu > Home item > Parameters.

How to work with Wordpress blog settings

October 16th, 2008

Wordpress blog settings are stored in the wp_options database table and can be read with the get_option($setting) function. This function applies pre_option_{setting} filters, checks whether the option is already loaded, and returns its value by fetching it from the database or from the cache.

Wordpress has more then 90 options but most frequently used of them are the following (in alphabet order):

 

  • blog_charset
  • blogname
  • date_format
  • default_category
  • default_ping_status
  • gmt_offset
  • home
  • permalink_structure
  • siteurl
  • time_format

There are several functions for managing options: update_option($name, $value), add_option($name, $value, $depricated, autoload), delete_option($name).

Most of the options can be modified in wp-admin. For example, the “Front page displays” option that specifies whether front page should display list of latest posts or specific page can be configured on the “Reading Settings” page in the wp-admin/options-reading.php file. After modifying, this setting is saved by the wp-admin/options.php file in the show_on_front, page_on_front, and page_for_posts options.

With this information we can create a simple function that checks whether the current page is the front page of a Wordpress site:

function is_front_page2() {
  if (’page’ == get_option(’show_on_front’)
    && 0 != ($id = get_option(’page_on_front’))
    && null != ($page = get_page($id)))
    return is_page($page->ID);
  return is_home();
}

is_front_page2 was chosen because the is_front_page function exists, but it returns wrong result when show_on_front = ‘page’ and page_on_front == 0 and page_for_posts != 0.

Creating new Joomla template

October 11th, 2008

You can download the GreenField template on this page: GreenField template for Joomla.

The simplest way to create a new template is to base it on one of the existent template. Joomla is shipped with three templates, beez, JA_Purity, and rhuk_milkyway. rhuk_milkyway is the default template so let’s copy it to the greenfield folder and modify its design.

Milkyway template

Milkyway template

The goal, Greenfield template.

The goal, Greenfield template.

First, the template information in templateDetails.xml should be changed because Joomla reads the template name from this file and now we have two rhuk_milkyway templates. To change it, open the greenfield\templateDetails.xml file and change template information tags as follows:

<name>Green Field</name>
<creationDate>10/08/08</creationDate>
<author>CMS Lamp</author>
<authorEmail>cms.lamp@gmail.com</authorEmail>
<authorUrl>http://cmslamp.com/</authorUrl>
<copyright></copyright>
<license>GNU/GPL</license>
<version>1.0.0</version>
<description>Nice green theme</description>

The params section in templateDetails.xml may be removed and the content of the params.ini file can be removed too. Then we can continue by editing index.php.

index.php has milkyway-related includes and HTML tags so let’s remove them: several links to styles, code related to text order (ltr/rtl), the id and class attrbites of the body tag, html tags in body tag. GreenField will not support complex layouting and some of the placeholders so all these content may be removed too (from index.php and templateDetails.xml).

We end up with a very simple index.php:

<?php
// no direct access
defined( '_JEXEC' ) or exit( 'Restricted access' );
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php echo $this->language;
?>" lang="<?php echo $this->language; ?>" >
<head>
<jdoc:include type="head" />
</head>
<body>
<!-- breadcrumb -->
<jdoc:include type="modules" name="breadcrumb" />
<!-- message -->
<jdoc:include type="message" />
<!-- left column -->
<jdoc:include type="modules" name="left" style="rounded" />
<!-- main column -->
<jdoc:include type="component" />
<!-- right column -->
<jdoc:include type="modules" name="right" style="xhtml"/>
<!-- page footer -->
<jdoc:include type="modules" name="syndicate" />
<!-- powered by -->
<?php echo JText::_('Powered by') ?> <a href="http://www.joomla.org">Joomla!</a>,
<a href="http://cmslamp.com/joomla-template/greenfield">Joomla template</a> by
<a href="http://cmslamp.com/">CMS Lamp</a>.
</body>
</html>

and templateDetails.xml:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE install PUBLIC "-//Joomla! 1.5//DTD template 1.0//EN"
"http://dev.joomla.org/xml/1.5/template-install.dtd">
<install version="1.5" type="template">
  <name>Green Field</name>
  <creationDate>10/08/08</creationDate>
  <author>CMS Lamp</author>
  <authorEmail>cms.lamp@gmail.com</authorEmail>
  <authorUrl>http://cmslamp.com/</authorUrl>
  <copyright></copyright>
  <license>GNU/GPL</license>
  <version>1.0.0</version>
  <description>Nice green theme</description>
  <files>
    <filename>index.php</filename>
    <filename>templateDetails.xml</filename>
    <filename>template_thumbnail.png</filename>
    <filename>params.ini</filename>
  </files>
  <positions>
    <position>menu</position>
    <position>breadcrumb</position>
    <position>left</position>
    <position>right</position>
    <position>syndicate</position>
  </positions>
</install>

Creating HTML template is a complex task, so I suppose that HTML template is available. In this case the next step is very simple: accuratelly copy the content from the HTML template to the GreenField Joomla template, placing <jdoc:include … /> in correct places.

jdoc modules include allows to select block decorator. It may be one of the standard decorators defined in templates\system\html\modules.php: none, table, horz, xhtml, rounded, and outline, or template-specific decorators from html\modules.php file of the particular template.

The GreenField template has one decorator for blocks, called gfblock, which applied to the top, menu, left, and right placeholders. This decorator adds nice border and caption for the module blocks. The top placeholder processed differently: menu module output is changed to match the HTML template menu.

To make GreenField looks similar to the HTML template, site headline and slogan patrameters should be added. After registering parameters in templateDetails.xml and set their default values in params.ini they will appear in template parameters in Joomla adminstrating section.

And the final step is adding theme files to templateDetails.xml.

You can download the GreenField template on this page: GreenField template for Joomla.

How Joomla template index.php works

October 8th, 2008

index.php is the main file of any Joomla template. This file is loaded by the CMS during displaying each page of the site. It inclides all necessary content, other PHP files, CSS styles, images and so on.

index.php may contain jdoc includes and PHP code blocks with custom PHP code. Since PHP is a very flexible language the code in PHP code blocks can do anything to build the output. Joomla CMS provides the developers with the API that simplifies the template development by providing shortcuts for frequently reused code fragments.

A few API examples:

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

<?php if($this->countModules(’left’)) : ?>
<div id="maincolumn">
<?php else: ?>
<div id="maincolumn_full">
<?php endif; ?>

As you may see on these examples, the index.php file is executed in the context of some object and this object has a few usefull methods and properties for template developers:

  • title - page title
  • description - page description
  • language - page language
  • params - collection of template parameters, defined in templateDescription.xml
  • template - name of the template
  • direction - document direction, ltr (left-to-right) or rtl (right-to-left)
  • countModules(condition) - counts modules based on the given condition

This object is an instance of the JDocumentHTML class, defined in the libraries\joomla\document\html\html.php file. By reviewing the code of that file you can find more information about properties and methods of this class.

jdoc:include is a shortcut to the $this->getBuffer(type, name, args) function call. jdoc:include and getBuffer function create corresponded renderer class and executes its render(…) method. The following renderers are available:

  • component - outputs the component
  • head - renders head HTML elements such as script, link, meta, style.
  • message - displays message queue
  • module - renders module blocks which are in the given placeholder.
  • modules - renders all modules in the given placeholder.

Among these renderers only module and modules can accept name and parameters. For the modules renderer the name argument contains placeholder name, for the module renderer the name contains module name that will be renderer.

The modules renderer calls the module renderer for each module placed in the placeholder and the module renderer calls JModuleHelper::renderModule(module, params) to render the module blocks.

JModuleHelper is defined in libraries\joomla\application\module\helper.php and contains methods for loading module settings from the database and rendering the module.

Module performs the following steps to render its content:

  1. Initialize parameters, which are based on attributes of the jdoc:include tag.
  2. Executing module PHP file from modules folder.
  3. Framing module output with decorating function from the templates\system\html\modules.php or templates\{current_template}\html\modules.php file.

Joomla Template Files

October 6th, 2008

Joomla template is set of files created with purpose to wrap up the content of the CMS into HTML tags with CSS rules and interractive JavaScript. The minimal template contains two files: templateDetails.xml and index.php.

Joomla reads templateDetails.xml to determine features template supports and files it contains. It also may contian definition of block placeholdes in the index.php file, template parameters, and author information.

index.php is the main template file. It contains page layout, may include CSS files, script files, and images.

Theme may be parametrized, in this case templateDetails.xml should contain definition of parameters, which usually dropdown lists and sets of radio buttons. Selected parameter values are saved in params.ini and this file should be writable by Joomla and listed in the templateDetails.xml file.

The index.html file, which you may see in a lot of Joomla themes, are usually blank and used to prevent Web server with directory indexing turned on from displaying theme files. This file, as other theme files, should be listed in templateDetails.xml in the files section.

The template_thumbnail.png file contains small preview of the Joomla CMS with the template applied. This PNG file should have the following dimensions: width 206px and height 150px. This file does not directly impact on how theme works, but it very usefull for users when they selecting the theme for their sites.

Read more: