Note:

If you want to create a new page for developers, you should create it on the Moodle Developer Resource site.

Themes overview: Difference between revisions

From MoodleDocs
Line 584: Line 584:
==Compiling LESS on the fly==
==Compiling LESS on the fly==
{{Moodle 2.7}}
{{Moodle 2.7}}
You can now provide a LESS file that will be compiled (and cached) on the fly. The purpose of this feature is to dynamically allow the customisation of LESS variables.
===Set up your theme===
# Create a .less file in a less folder. Eg. <code>theme/yourtheme/less/myfile.less</code>
# Edit your theme config file, and set $THEME->'''lessfile''' to the name of your file (do not include .less). Eg. <code>$THEME->lessfile = 'myfile'</code>
That's it, the LESS file will be compiled and included in the page on the fly, but that is not very useful yet.
Please note that any file referenced in $THEME->sheets that shares the same name than the LESS file will be silently ignored.
===Inheriting from a parent===
Even if your theme is inheriting from a parent, the LESS file itself will not inherit from anything, this is something you should do manually. For instance, if you want your LESS file to include all of the LESS code provided by ''theme_bootstrapbase'', usually to change the variables, you need to manually import the file like this:
<code>
@import "../../bootstrapbase/less/moodle.less";
</code>
The path needs to be relative and not absolute. You would definitely want to add that rule first in your file and add anything else below it.
===Programmatically injecting LESS===
There are two theme options to specify a callback function that you need to know about:
# $THEME->'''extralesscallback''': To return raw LESS code to be injected.
# $THEME->'''lessvariablescallback''': To return an array of variables and their values.
Typically you will want to simply inject variables, but if you need to perform more complex manipulations, you can return some raw LESS code. The variables returned by the callback are always injected last.
===Performance===
Compiling LESS on the fly is a slow operation, and even though the result is cached you should be aware of it. If you have enabled the configuration setting ''themedesignermode'' you will definintely notice the slowness as the cache only lives for a very short period of time. Ideally your theme should precompile the LESS into CSS, but if you want to provide theme settings to your user, then using this feature is for you.


==Unobvious Things==
==Unobvious Things==

Revision as of 04:11, 8 April 2014

Welcome to the new world of themes in Moodle 2.x!

A Moodle theme allows the user to change the look and feel of a Moodle site. Themes can be applied on the site, category, course and activity levels by users with permissions to do so. Themes can be designed for specific devices such as mobile phones or tablets. This page explains how themes work in Moodle and is intended to help you create or modify most themes for Moodle 2.0

You can use contributed themes or create your entire own to share with the community. Themes can also be based on parent themes with only few customizations. Themes accomplish this using CSS, changing the underlying markup structure and also adding Javascript to add more advanced behaviors.

Most theme developers simply add a few changes to their new theme by basing it on an existing one. The Moodle Theme architecture is designed in such a way whereby the base theme will act as a fall-back that is used when nothing has been defined in the theme based on it. This makes it easy to create new themes that simply seek out to make minor changes.


What's new in 2.7

Moodle 2.7


Compiling LESS

Themes now have the ability to compile a LESS file on the fly. This was intended to be used for dynamic injection of LESS code or variables. (MDL-44357)

What's new in 2.6

Moodle 2.6


Fonts

CSS3 fonts can be now used in plugins, core and moodle themes. It is very similar to images in pix subdirectories (MDL-23493).

Chat Activity

The Chat room window is now also styled via bootstrapbase. Themes based on bootstrapbase can now directly style or use 'customcss' to style the chat window now. (MDL-42711)

What's new in 2.5

Moodle 2.5


There is a new Bootstrap base theme. See Clean theme for more information.

What's new in 2.4

Moodle 2.4


HTML 5 doctype

By default Moodle is sending HTML5 doctype. Themes designers may decide to force old xhtml strict mode, but it is strongly discouraged and the site will not pass strictness validation. (MDL-34299)

Internet Explorer standards mode

Since 2.4 Moodle automatically sends X-UA-Compatible edge header, this should prevent Internet Explorer from switching to quirks or compatibility modes (MDL-36524). There is also a new workaround for intranet servers which previously identified recent IE browsers as IE7. (MDL-36481)

SVG icons

Most modern browsers support SVG icons. The benefit is that SVG scales perfectly to any screen resolution or zoom. It is now possible to add icons in SVG format to pix directories, Moodle uses SVG in supported browsers and PNG in legacy browsers. (MDL-22955)

Please note that IE9 does not handle scaling of standard SVG icons properly, you may have to manually execute a special script from theme/base/cli/svgtool.php to alter the icons to be compatible with buggy IE9. (MDL-36436)

What's new in 2.0

The theme system was completely redesigned in Moodle 2.0. Known issues have been addressed and new features have been added to meet community requests.

Unfortunately it was not possible to maintain backward compatibility, so all Moodle 1.x themes need to be recreated for Moodle 2.0.

Major changes include:

  • Clearer and more consistent CSS classes and IDs throughout all pages in Moodle
  • Introduction of layout files (templates) describing overall layout HTML for many different types of pages in Moodle.
  • Introduction of renderers, which produce the smaller "parts" of a HTML page. Advanced themes can choose to override these too if they choose.
  • Introduction of standard methods for adding Javascript to themes.
  • Easier control over icons and images in Moodle.
  • The old "standard" theme has been split into two themes:
    • base - contains absolutely basic layout, and
    • standard - which adds CSS to the base theme to make it look like the old standard theme.
  • Performance tuning: In normal production mode CSS files are combined into a single optimised file, and both CSS and JavaScript files are minimised to ensure there are no wasted connections or traffic. Files are heavily cached, but also versioned, so that users never need to clear their caches.

The structure of a theme

Some important things to know when building good themes:

  1. config.php - this file is required in every theme. It defines configuration settings and definitions required to make the theme work in Moodle. These include theme, file, region, default region and options.
  2. Layouts and layout files - in config.php there is one definition for each page type (see Appendix A: Theme layouts for a list of over 12 types). Each page type definition tells Moodle which layout file will be used, what block regions this page type should display and so on. The layout file contains the HTML and the minimum PHP required to display basic structure of pages. (If you know Moodle 1.9, it's like a combination of header.html and footer.html).
  3. The base theme - is not intended to be used for production sites. It sets up the simplest possible generic layout and includes only CSS essential to that layout or to Moodle as a whole. It tries not to make any unnecessary rules and makes as few assumptions as possible. It's the perfect base on which to start designing a theme, as there are very few colours, borders, margins, and alignments to override. You can just start adding what you need.

Files and folders

A theme's files are placed in a folder with under moodle/theme folder and have subfolders. They are laid out like this:

Directory File Description
/ config.php Contains all of the configuration and definitions for each theme
/ lib.php Contains speciality classes and functions that are used by theme
/ renderers.php Contains any custom renderers for the theme.
/ settings.php Contains custom theme settings. These local settings are defined by the theme allowing the theme user to easily alter something about the way it looks or operates. (eg a background colour, or a header image)
/ version.php Contains the theme name, version number and Moodle version requirements for using the theme
/fonts/ *.woff, *.ttf, *.eot, *.svg, *.otf Theme fonts (since 2.6).
/fonts_core/ *.woff, *.ttf, *.eot, *.svg, *.otf Contains fonts that override standard core fonts (since 2.6).
/fonts_plugins/plugintype/pluginname/ *.woff, *.ttf, *.eot, *.svg, *.otf Contains fonts that override plugin fonts (since 2.6).
/javascript/ *.js All specialty JavaScript files the theme requires should be located in here.
/lang/ Any special language files the theme requires should be located in here.
/layout/ *.php Contains the layout files for the theme.
/pix/ *.png, *.jpg, *.gif, *.svg Contains any images the theme makes use of either in CSS or in the layout files.
/pix/ favicon.ico The favicon to display for this theme.
/pix/ screenshot.png A screenshot of the theme to be displayed in on the theme selection screen.
/pix_core/ *.png, *.jpg, *.gif, *.svg Contains images that override standard core images.
/pix_plugins/plugintype/pluginname/ *.png, *.jpg, *.gif, *.svg Contains images that override plugin images.
/style/ *.css Default location for CSS files.

There are also several other places that stylesheets can be included from (see the CSS how and why section below).

It is possible to override icons used in base themes without interfering with core code by placing these in dataroot/pix and dataroot/pix_plugins. Where a theme extends a base theme and provides its own icons, these icons will still be used.

Theme options

All theme options are set within the config.php file for the theme. The settings that are most used are: parents, sheets, layouts, and javascripts. Have a look at the theme options table for a complete list of theme options which include lesser used specialised or advanced settings.


Basic theme config example

Lets have a look at a basic theme configuration file and the different bits that make it up: $THEME->name = 'newtheme';

$THEME->parents = array(

   'base'

);

$THEME->sheets = array(

   'admin',
   'blocks',
   'calendar',
   'course',
   'grade',
   'message',
   'question',
   'user'

);

$THEME->layouts = array(

   'base' => array(
       'theme' => 'newtheme',
       'file' => 'general.php',
       'regions' => array(),
   ),
   'standard' => array(
       'theme' => 'newtheme',
       'file' => 'general.php',
       'regions' => array('side-pre', 'side-post'),
       'defaultregion' => 'side-post',
   )
   //.......

);

$THEME->javascripts_footer = array(

   'navigation'

);

Basic theme example settings explained

First up you will notice everything is added to $THEME. This is the theme's configuration object, it is created by Moodle using default settings and is then updated by whatever settings you add to it.

$THEME->name
The first setting, is the theme's name. This should simply be whatever your theme's name is, most likely whatever you named your theme directory.
$THEME->parents
This defines the themes that the theme will extend. In this case it is extending only the base theme.
$THEME->sheets
An array containing the names of the CSS stylesheets to include for this theme. Note that it is just the name of the stylesheet and does not contain the directory or the file extension. Moodle assumes that the theme's stylesheets will be located in the styles directory of the theme and have .css as an extension.
$THEME->layouts
In this example, two layouts have been defined to override the layouts from the base theme. For more information see the layouts section below.
$THEME->javascripts_footer
The final setting is to include a JavaScript file. Much like stylesheets, you only need to provide the files name. Moodle will assume it is in your themes JavaScript directory and be a .js file.

Note: When you first begin writing themes, make sure you take a look at the configuration files of the other themes that get shipped with Moodle. You will get a good picture of how everything works, and what is going on in a theme, simply by reading it and taking notice of what it is including or excluding.

CSS

Locations of CSS files

First lets look at where CSS can be included from within Moodle:

\theme\themename\style\*.css
This is the default location for all of the stylesheets that are used by a theme and the place which should be used by a theme designer.

New theme developers should note that the order in which CSS files are found and included creates a hierarchy. This order ensures that the rules, within a theme's style sheets, take precedence over identical rules in other files that may have been introduced before. This can both extend another files definitions (see parent array in the config file) and also ensures that the current theme's CSS rules/definitions have the last say.

There are other locations that can be used (although very rarely) to include CSS in a page. A developer of a php file can manually specify a stylesheet from anywhere within Moodle, like the database. Usually, if code is doing this, it is because there is a non-theme config or plugin setting that contains information requires special CSS information. As a theme designer you should be aware of, but not have to worry about, these locations of CSS files. Here are some examples:

{pluginpath}\styles.css e.g. \block\blockname\styles.css or \mod\modname\styles.css
Every plugin can have its own styles.css file. This file should only contain the required CSS rules for the module and should not add anything to the look of the plugin such as colours, font sizes, or margins other than those that are truly required.
Theme specific styles for a plugin should be located within the themes styles directory.
{pluginpath}\styles_themename.css
This should only ever be used by plugin developers. It allows them to write CSS that is designed for a specific theme without having to make changes to that theme. You will notice that this is never used within Moodle and is designed to be used only by contributed code.

As theme designers, we will only use the first method of introducing CSS: adding rules to a stylesheet file located in the theme's style directory.

Moodle's core CSS organisation

The next thing to look at is the organisation of CSS and rules within a theme. Although as a theme designer it is entirely up to you as to how you create and organise your CSS. Please note that within the themes provided in the standard install by Moodle there is a very clear organisation of CSS.

First is the pagelayout.css file. This contains the CSS required to give the layouts their look and feel. It doesn't contain any rules that affect the content generated by Moodle.

Next is the core.css file. If you open up core you will notice that it contains all manner of general (usually simple) rules that don't relate to a specific section of Moodle but to Moodle as a whole.

There can also be rules that relate to specific sections. However, this is done only when there are only a handful of rules for that section. These small clusters of rules are grouped together and separated by comments identifying for which section each relates.

Finally there are all the other CSS files, you will notice that there is a file for each section of Moodle that has a significant collection of rules.

For those who are familiar with Moodle 1.9 theme's, this organisation will be a big change. In 1.9, CSS was organised by its nature (for example: colours, layout, other).

How to write effective CSS rules within Moodle

In Moodle 2.0, writing good CSS rules is incredibly important.

Due to performance requirements and browser limitations, all of the CSS files are combined into a single CSS file that gets included every time. This means that rules need to be written in such a way as to minimise the chances of a collision leading to unwanted styles being applied. Whilst writing good CSS is something most designers strive for we have implemented several new body classes and prompt developers to use appropriate classnames.

<body> CSS id and classes

As of Moodle 2.0 the ID tag that gets applied to the body will always be a representation of the URI. For example if you are looking at a forum posting and the URI is '/mod/forum/view.php' then the body tags ID will be '#page-mod-forum-view'.

As well as the body's ID attribute the URI is also exploded to form several CSS classes that get added to the body tag, so in the above example '/mod/forum/view' you would end up with the following classes being added to the body tag '.path-mod', '.path-mod-forum'. Note that '.path-mod-forum-view' is not added as a class, this is intentionally left out to lessen confusion and duplication as rules can relate directly to the page by using the ID and do not require the final class.

The body ID and body classes described above will form the bread and butter for many of the CSS rules you will need to write for your theme, however there are also several other very handy classes that get added to the body tag that will be beneficial to you once you start your journey down the rabbit hole that is themeing. Some of the more interesting classes are listed below.

  • If JavaScript is enabled then 'jsenabled' will be added as a class to the body tag allowing you to style based on JavaScript being enabled or not.
  • Either 'dir-rtl' or 'dir-ltr' will be added to the body as a class depending on the direction of the language pack: rtl = right to left, ltr = left to right. This allows you to determine your text-alignment based on language if required.
  • A class will be added to represent the language pack currently in use, by default en_utf8 is used by Moodle and will result in the class 'lang-en_utf8' being added to the body tag.
  • The wwwroot for Moodle will also be converted to a class and added to the body tag allowing you to stylise your theme based on the URL through which it was reached. e.g. http://sam.moodle.local/moodle/ will become '.sam-moodle-local—moodle'
  • If the current user is not logged then '.notloggedin' will be added to the body tag.

What does all of this look like in practise? Well using the above example /mod/forum/view.php you would get at least the following body tag: <body id=”page-mod-forum-view” class=”path-mod path-mod-forum” />

Writing your rules

By following the CSS coding style and CSS best-practices and understanding the cascading order of CSS a theme developer will reduce collisions and lines of CSS that is written. CSS classes have been placed where it is believed anyone may want to apply their own styles.

When starting to write rules make sure that you have a good understanding of where you want those rules to be applied, it is a good idea to make the most of the body classes mentioned above. If you want to write a rule for a specific page make use of the body tag's ID, e.g.:

#page-mod-forum-view .forumpost {

   border: 1px solid blue;

}

If you want to write a rule that will be applied all throughout the forum.:

.path-mod-forum .forumpost {

   border: 1px solid blue;

}

The other very important thing to take into consideration is the structure leading up to the tag you want to style. Browsers apply conflicting styles with priority on the more specific selectors. It can be very beneficial to keep this in mind and write full selectors that rely on the structure of the tags leading to the tag you wish to style.

By making use of body id's and classes and writing selectors to take into account the leading structure you can greatly minimise the chance of a collision both with Moodle now and in the future.

Layouts

Layouts are defined in config.php.

All themes are required to define the layouts they wish to be responsible for as well as create; however, many layout files are required by those layouts. If the theme is overriding another theme then it is a case of deciding which layouts this new theme should override. If the theme is a completely fresh start then you will need to define a layout for each of the different possibilities.

It is also important to note that a new theme that will base itself on another theme (overriding it) does not need to define any layouts or use any layout files if there are no changes that it wishes to make to the layouts of the existing theme. The standard theme in Moodle is a good example of this as it extends the base theme simply adding CSS to achieve its look and feel.

As mentioned earlier, layouts are defined in config.php within $THEME->layouts. The following is an example of one such layout definition: $THEME->layouts = array(

   // Standard layout with blocks, this is recommended for most pages with general information
   'standard' => array(
       'theme' => 'base',
       'file' => 'general.php',
       'regions' => array('side-pre', 'side-post'),
       'defaultregion' => 'side-post'
   )

) The first thing Moodle looks at is the name of the layout, in this case it is `standard` (the array key in PHP), it then looks at the settings for the layout, this is the theme, file, regions, and default region. There are also a couple of other options that can be set by a layout.

theme
is the theme the layout file exists in. That's right: you can make use of layouts from other installed themes. Optional
file
is the name of the layout file this layout wants to use. Required
regions
is the different block regions (places you can put blocks) within the theme. Required
defaultregion
is the default location when adding new blocks. Required if regions is non-empty, otherwise optional
options
an array of layout specific options described in detail below. Optional

The theme is optional. Normally the the layout file is looked for in the current theme, or, if it is not there, in the parent theme. However, you can use a layout file from any other theme by giving the theme name here.

You can define whatever regions you like. You just need to pick a name for each one. Most themes just use one or both of side_pre and side_post, which is like 'left side' and 'right side', except in right to left languages, when they are reversed. If you say in config.php that your the layout provides regions called 'fred' and 'barney', then you must call $OUTPUT->blocks_for_region('fred') and $OUTPUT->blocks_for_region('barney') somewhere in the layout file.

The final setting options is a special case that only needs to be set if you want to make use of it. This setting allows the theme designer to specify special options that they would like to create that can be later accessed within the layout file. This allows the theme to make design decisions during the definition and react upon those decisions in what ever layout file is being used.

One such place this has been used is within the base theme. If you take a look first at theme/base/config.php you will notice that several layouts specify options nonavbar and nofooter which can both be set to either true or false. Then if we take a look at theme/base/layout/general.php you will spot lines like the following: <?php $hasnavbar = (empty($PAGE->layout_options['nonavbar']) && $PAGE->has_navbar()); $hasfooter = (empty($PAGE->layout_options['nofooter'])); ?> ............ <?php if ($hasnavbar) { ?>

<?php } ?> What you are seeing here is the use of those settings from the layout within the layout file. In this case it is being used to toggle the display of the navigation bar and page footer.

Layout files

A layout file is a file that contains the core HTML structure for a layout including the header, footer, content and block regions. For those of you who are familiar with themes in Moodle 1.9 this is simply header.html and footer.html combined. Of course it is not all HTML, there are bits of HTML and content that Moodle needs to put into the page, within each layout file this will be done by a couple of simple PHP calls to get bits and pieces including content.

Before learning more it is good to understand the two primary objects that will be used in your layout files: $OUTPUT and $PAGE.

$OUTPUT is an instance of the core_renderer class which is defined in lib/outputrenderers.php. Each method is clearly documented there, along with which is appropriate for use within the layout files.

$PAGE is an instance of the moodle_page class defined in lib/pagelib.php. Most of the things you will want to use are the properties that are all documented at the top of the file. If you are not familiar with PHP properties, you access them like $PAGE->activityname, just like fields of an ordinary PHP object. (However, behind the scenes the value you get is produced by calling a function. Also, you cannot change these values, they are read-only. However, you don't need to understand all that if you are just using these properties in your theme.)

The following is a very simple layout file to illustrate the different bits that make it up: <?php echo $OUTPUT->doctype() ?> <html <?php echo $OUTPUT->htmlattributes() ?>> <head>

   <title><?php echo $PAGE->title ?></title>
   <?php echo $OUTPUT->standard_head_html() ?>

</head> <body id="<?php p($PAGE->bodyid) ?>" class="<?php p($PAGE->bodyclasses) ?>"> <?php echo $OUTPUT->standard_top_of_body_html() ?>

<?php echo $PAGE->heading ?>

<?php echo $OUTPUT->login_info(); echo $PAGE->headingmenu; ?>
           <?php echo $OUTPUT->blocks_for_region('side-pre') ?>
           <?php echo core_renderer::MAIN_CONTENT_TOKEN ?>
           <?php echo $OUTPUT->blocks_for_region('side-post') ?>
           <?php
           echo $OUTPUT->login_info();
           echo $OUTPUT->home_link();
           echo $OUTPUT->standard_footer_html();
           ?>

<?php echo $OUTPUT->standard_end_of_body_html() ?> </body> </html>

We assume you know enough HTML to understand the basic structure above, but let's explain the PHP code since that is less obvious. <?php echo $OUTPUT->doctype() ?> This occurs at the VERY top of the page, it must be the first bit of output and is responsible for adding the (X)HTML document type definition to the page. This of course is determined by the settings of the site and is one of the things that the theme designer has no control over.

<html <?php echo $OUTPUT->htmlattributes() ?>> Here we have started writing the opening html tag and have asked Moodle to give us the HTML attributes that should be applied to it. This again is determined by several settings within the actual HTML install.

<?php echo $PAGE->title ?> This gets us the title for the page.

<?php echo $OUTPUT->standard_head_html() ?> This very important call gets us the standard head HTML that needs to be within the HEAD tag of the page. This is where CSS and JavaScript requirements for the top of the page will be output as well as any special script or style tags.

<body id="<?php p($PAGE->bodyid); ?>" class="<?php p($PAGE->bodyclasses); ?>"> Much like the html tag above we have started writing the body tag and have asked for Moodle to get us the desired ID and classes that should be applied to it.

<?php echo $PAGE->heading; ?>

<?php echo $OUTPUT->login_info(); echo $PAGE->headingmenu; ?>

Here we are creating the header for the page. In this case we want the heading for the page, we want to display the login information which will be the current users username or a link to log in if they are not logged in, and we want the heading menu if there is one.

<?php echo $OUTPUT->blocks_for_region('side-pre') ?> Here we get the HTML to display the blocks that have been added to the page. In this case we have asked for all blocks that have been added to the area labelled side-pre.

<?php echo core_renderer::MAIN_CONTENT_TOKEN ?> This is one of the most important calls within the file, it determines where the actual content for the page gets inserted.

<?php echo $OUTPUT->blocks_for_region('side-post') ?> Here we get the HTML to display the blocks that have been added to the page. In this case we have asked for all blocks that have been added to the area labelled side-post.

<?php echo $OUTPUT->login_info(); echo $OUTPUT->home_link(); echo $OUTPUT->standard_footer_html(); ?> This final bit of code gets the content for the footer of the page. It gets the login information which is the same as in the header, a home link, and the standard footer HTML which like the standard head HTML contains all of the script and style tags required by the page and requested to go in the footer.

Note: Within Moodle 2.0 most of the JavaScript for the page will be included in the footer. This greatly helps reduce the loading time of the page.

When writing layout files think about the different layouts and how the HTML that each makes use of will differ. You will most likely find you do not need a different layout file for each layout, most likely you will be able to reuse the layout files you create across several layouts. You can of course make use of layout options as well to further reduce the number of layout files you need to produce.

Of course as mentioned above if you are customising an existing theme then you may not need to create any layouts or layout files at all.

Language File

You need to create a language file for your theme with a few standard strings in it. At a minimum create a file called lang/en/theme_themename.php in your theme folder. For example, the 'standard' theme has a language file called lang/en/theme_standard.php.

You must define the following lines in your file (example is from standard theme, adapt as required):

$string['pluginname'] = 'Standard'; $string['region-side-post'] = 'Right'; $string['region-side-pre'] = 'Left'; $string['choosereadme'] = 'This theme is a very basic white theme, with a minimum amount of

CSS added to the base theme to make it actually usable.';

Without the above you will get notices for the missing strings.

Making use of images

Right at the start when listing the features of the new themes system one of the features mentioned was the ability to override any of the standard images within Moodle from within your theme. At this point we will look at both how to make use of your own images within your theme, and secondly how to override the images being used by Moodle. So first up a bit about images within Moodle,

  1. Images you want to use within your theme need to be located within your theme's pix directory.
  2. You can use sub directories within the pix directory of your theme.
  3. Images used by Moodle's core are located within the pix directory of Moodle.
  4. Modules, blocks and other plugins should also store their images within a pix directory.

So making use of your own images first up. Lets assume you have added two image files to the pix directory of your theme.

  • /theme/yourthemename/pix/imageone.jpg
  • /theme/yourthemename/pix/subdir/imagetwo.png

Notice that one image is a JPEG image, and the second is a PNG. Also the second image is in a subdirectory.

The following code snippet illustrates how to make use of your images within HTML, such as if you wanted to use them within a layout file. <img src="<?php echo $OUTPUT->pix_url('imageone', 'theme');?>" alt="" /> <img src="<?php echo $OUTPUT->pix_url('subdir/imagetwo', 'theme');?>" alt="" />

DO NOT include the image file extension. Moodle will work it out automatically and it will not work if you do include it.

In this case rather than writing out the URL to the image we use a method of Moodle's output library. Its not too important how that functions works but it is important that we use it as it is what allows images within Moodle to be over-rideable.

The following is how you would use the images from within CSS as background images. .divone {

   background-image: url(imageone);

}

.divtwo {

   background-image: url(subdir/imagetwo);

} If this case we have to use some special notations that Moodle looks for. Whenever Moodle hands out a CSS file it first searches for all something tags and replaces them with what is required.

The final thing to notice with both of the cases above is that at no point do we include the images file extension. The reason for this leads us into the next topic, how to override images.

From within a theme you can VERY easily override any standard image within Moodle by simply adding the replacement image to the theme's pix directory in the same sub directory structure as it is in Moodle. So for instance we wanted to override the following two images:

  1. /pix/moodlelogo.gif
  2. /pix/i/user.gif

We would simply need to add our replacement images to the theme in the following locations

  1. /theme/themename/pix_core/moodlelogo.gif
  2. /theme/themename/pix_core/i/user.gif

Note that we have created a pix_core directory in our theme. For module images we need a pix_mod directory.

Now the other very cool thing to mention is that Moodle looks for not just replacements of the same image type (jpg, gif, etc...) but also replacements in any image format. This is why above when working with our images we never specified the images file extension. This means that the following would also work:

  1. /theme/themename/pix_core/moodlelogo.png
  2. /theme/themename/pix_core/i/user.bmp

For a more detailed description of how this all works see the page on Using images in a theme.

Adding custom fonts

Moodle 2.6


CSS3 standard introduced the possibility to specify custom fonts, see CSS3 Fonts tutorial.

Since 2.6 Moodle includes support for plugin or theme fonts. It is very similar to theme images and pix subdirectories.

Font file locations

Depending on where you intend to use the font put it into one of the following locations:

  • /lib/fonts/ - fonts used in core
  • /plugindir/fonts/ - fonts used by plugin
  • /theme/sometheme/fonts/ - theme specific fonts

You can also override core and plugin fonts in theme:

  • /theme/sometheme/fonts_core/ - overridden core fonts
  • /theme/sometheme/fonts_plugins/plugintype_pluginname/ - overridden fonts of some plugin

Notes:

  • subdirectories are not allowed
  • use only lowercase alphanumeric characters and underscore in font file names
  • WOFF (Web Open Font Format), TTF (True Type Fonts), OTF (OpenType Fonts), SVG (Scalable Vector Graphic) and EOT (Embedded OpenType) fonts are supported, but for the sake of humanity (And MDL_15169 ) please use only WOFF fonts to encourage the quick death of IE8.

CSS placeholders

@font-face {

   font-family: ThreeDumb;
   src: url(3dumb.woff);

}

The placeholder references file /mod/book/fonts/3dumb.woff, the new fontface could be for example used for book headings:

.path-mod-book .book_chapter_title {

   font-family: ThreeDumb;

}

If you want to use some font in theme only, you can for example:

@font-face {

   font-family: goodDogFont;
   src: url(good_dog.woff);

}

a {font-family:goodDogFont;}

The font would be stored in /theme/yourtheme/fonts/good_dog.woff file.

More free fonts

Please respect all licenses for font redistribution, you can get some nice free fonts from http://www.fontsquirrel.com for example.

Warning

This is not intended for forcing of something like Comic Sans on all your visitors...

Compiling LESS on the fly

Moodle 2.7


You can now provide a LESS file that will be compiled (and cached) on the fly. The purpose of this feature is to dynamically allow the customisation of LESS variables.

Set up your theme

  1. Create a .less file in a less folder. Eg. theme/yourtheme/less/myfile.less
  2. Edit your theme config file, and set $THEME->lessfile to the name of your file (do not include .less). Eg. $THEME->lessfile = 'myfile'

That's it, the LESS file will be compiled and included in the page on the fly, but that is not very useful yet.

Please note that any file referenced in $THEME->sheets that shares the same name than the LESS file will be silently ignored.

Inheriting from a parent

Even if your theme is inheriting from a parent, the LESS file itself will not inherit from anything, this is something you should do manually. For instance, if you want your LESS file to include all of the LESS code provided by theme_bootstrapbase, usually to change the variables, you need to manually import the file like this:

@import "../../bootstrapbase/less/moodle.less";

The path needs to be relative and not absolute. You would definitely want to add that rule first in your file and add anything else below it.

Programmatically injecting LESS

There are two theme options to specify a callback function that you need to know about:

  1. $THEME->extralesscallback: To return raw LESS code to be injected.
  2. $THEME->lessvariablescallback: To return an array of variables and their values.

Typically you will want to simply inject variables, but if you need to perform more complex manipulations, you can return some raw LESS code. The variables returned by the callback are always injected last.

Performance

Compiling LESS on the fly is a slow operation, and even though the result is cached you should be aware of it. If you have enabled the configuration setting themedesignermode you will definintely notice the slowness as the cache only lives for a very short period of time. Ideally your theme should precompile the LESS into CSS, but if you want to provide theme settings to your user, then using this feature is for you.

Unobvious Things

Getting Your Theme to Appear Correctly in Theme Selector

If you follow the examples on this page to the letter, when you go to the Theme Selector page you may be discouraged to find that your theme does not appear like the other themes do. In fact, instead of your theme's name, you will see something along the lines of [[pluginname]].

To correct this, you must add the theme/THEMENAME/lang/en/theme_THEMENAME.php file, where THEMENAME is the name of the theme folder. Inside that file, add the string "$string['pluginname'] = 'THEMENAME'; ". Make THEMENAME the name of your theme, however you want it displayed in the Theme selector.

Also, make sure to change your config.php file and version.php file to reflect the correct name:

In config.php: $THEME->name = 'NAME';

In version.php: $plugin->component = 'theme_NAME'; // Full name of the plugin (used for diagnostics)

The screenshot for the theme should be about 500x400 px.

Required theme divs

Some parts of Moodle may rely on particular divs, for example the div with id 'page-header'.

Consequently all themes must include at least the divs (with the same ids) that are present in the 'base' theme.

Missing out these elements may result in unexpected behaviour within specific modules or other plugins.

Appendix A

Theme options as of 8th April 2014

Setting Effect
$THEME->blockrtlmanipulations Allows the theme to manipulate how the blocks are displayed in a right-to-left language.
$THEME->csspostprocess Allows the user to provide the name of a function that all CSS should be passed to before being delivered.
$THEME->doctype The doctype of the served documents.
$THEME->editor_sheets An array of stylesheets to include within the body of the editor.
$THEME->enablecourseajax If set to false the course AJAX features will be disabled.
$THEME->enable_dock If set to true the side dock is enabled for blocks
$THEME->extralesscallback The name of a function that will return some LESS code to inject at the end of the LESS file specified in $THEME->lessfile. (Since 2.7)
$THEME->filter_mediaplugin_colors Used to control the colours used in the small media player for the filters
$THEME->hidefromselector Used to hide a theme from the theme selector (unless theme designer mode is on). Accepts true or false.
$THEME->javascripts An array containing the names of JavaScript files located in /javascript/ to include in the theme. (gets included in the head)
$THEME->javascripts_footer As above but will be included in the page footer.
$THEME->larrow Overrides the left arrow image used throughout Moodle
$THEME->layouts An array setting the layouts for the theme
$THEME->lessfile The name of a LESS file in the theme's less/ folder to compile on the fly. Sheets with the same name will be ignored. (Since 2.7)
$THEME->lessvariablescallback The name of a function that will modify some LESS variables before compiling the LESS file specified in $THEME->lessfile. (Since 2.7)
$THEME->name Name of the theme. Most likely the name of the directory in which this file resides.
$THEME->parents An array of themes to inherit from. If the theme you inherit from inherits from a parent as well, you need to indicate the grand parent here too.
$THEME->parents_exclude_javascripts An array of JavaScript files NOT to inherit from the themes parents
$THEME->parents_exclude_sheets An array of stylesheets not to inherit from the themes parents
$THEME->plugins_exclude_sheets An array of plugin sheets to ignore and not include.
$THEME->rarrow Overrides the right arrow image used throughout Moodle
$THEME->renderfactory Sets a custom render factory to use with the theme, used when working with custom renderers.
$THEME->resource_mp3player_colors Controls the colours for the MP3 player
$THEME->sheets An array of stylesheets to include for this theme. Should be located in the theme's style directory.
$THEME->supportscssoptimisation When set to 'FALSE' then the theme will not be affected by the 'CSS Optimiser'. The 'CSS Optimiser' is enabled in Development > Experimental > Experimental settings. When it is enabled CSS will be run through an optimisation process before being cached. The optimiser processes the CSS removing duplicate rules and styles, as well as white space removable and reformatting. Please note turning this on at the same time as theme designer mode is awful for performance but will help theme designers create optimised CSS.
$THEME->yuicssmodules An array of YUI CSS modules to be included.

The different layouts as of 21st April 2013

Layout Purpose
base Most backwards compatible layout without the blocks - this is the layout used by default.
standard Standard layout with blocks, this is recommended for most pages with general information.
course Main course page.
coursecategory Use for browsing through course categories.
incourse Default layout while browsing a course, typical for modules.
frontpage The site home page.
admin Administration pages and scripts.
mydashboard My dashboard page.
mypublic My public page.
login The login page.
popup Pages that appear in pop-up windows - no navigation, no blocks, no header.
frametop Used for legacy frame layouts only. No blocks and minimal footer.
embedded Used for embedded pages, like iframe/object embedded in moodleform - it needs as much space as possible
maintenance Used during upgrade and install. This must not have any blocks, and it is a good idea if it does not have links to other places - for example there should not be a home link in the footer.
print Used when the page is being displayed specifically for printing.
redirect Used when a redirection is occurring
report Used for reports.
secure Used for safebrowser and securewindow.

See also

Moodle 2.2+

Moodle Bootstrap Themes - Moodle 2.5+