Extension:ConditionalTemplate

From MediaWiki.org

Jump to: navigation, search
Manual on MediaWiki Extensions
List of MediaWiki Extensions
ConditionalTemplate

Release status: stable

Implementation Parser function, Extended syntax
Description Enables the conditional execution of a template.
Author(s) user:jldupont
Version check SVN @ download link
MediaWiki tested on 1.8.2 and 1.10
Download [1]

Contents

[edit] Purpose

The purpose of this extension is to enable conditional execution of a template.

The extension is especially useful if one relies on a complex 'stack' of templates to render a page and would rather make this as generic as possible. The conditional inclusion of a specified page enables, for example, definition of one master template which includes various 'header' / 'footer' pages depending on the namespace of inclusion.

[edit] Usage

{{#template:article title to include upon 'true' condition|condition}}

[edit] Example

 {{#template:HeaderPageNameForCategoryNamespace|
  {{#ifeq:{{NAMESPACE}}|Category|1|0}}
 }}

The above example will transclude the page 'HeaderPageNameForCategoryNamespace' if the call is made from a page residing in the Category namespace.

[edit] Source Code

<?php
 
/**
 * ConditionalTemplate
 * @package MediaWiki
 * @subpackage Extensions
 * @author Jean-Lou Dupont - http://bluecortex.com
 *
 * This extension enables the conditional transclusion of an article.
 * The syntax is the following:
 * {{#template:page | condition}}
 * where 'page' is the desired MW article
 * and 'condition' === true  --> page is transcluded
 *     'condition' === false --> page is not transcluded
 *
 * HISTORY:
 * v1.0
 */
$wgExtensionCredits['parserhook'][] = array(
  'name'    => "ConditionalTemplate [http://www.bluecortex.com]",
  'version' => '$LastChangedRevision: 202 $',
  'author'  => 'Jean-Lou Dupont [http://www.bluecortex.com]' 
);
 
$wgExtensionFunctions[]         = 'efCondTemplateSetup';
$wgHooks['LanguageGetMagic'][]  = 'efCondTemplateGetMagic';
 
function efCondTemplateGetMagic( &$magicWords, $langCode ) 
{
  $magicWords['template'] = array( 0, 'template' );
  return true;
}
 
function efCondTemplateSetup()
{
  global $wgParser;
  $wgParser->setFunctionHook( 'template', 'efCondTemplateExec' );      
}
 
function efCondTemplateExec(&$parser, $page, $cond = false )
{
  return ($cond ? efCondTemplateLoadPage($page) : '' );
}
 
#
# LoadPage function
# 
function efCondTemplateLoadPage( $p )
{
  $title = Title::newFromText( $p );
  if ( $title->getArticleID() == 0 )
    $text = "<b>[[".$p.']]</b>';
  else
  {
    $article = new Article( $title );
    $text = $article->getContent();
  }
 
  return $text;
}
?>

[edit] Dynamic Pages

This extension can be used in conjunction with Extension:ParserPhase2 to allow for more dynamic pages.

(($#template: page | condition $))
Personal tools