Manual:Plantillas HTML

From mediawiki.org
This page is a translated version of the page Manual:HTML templates and the translation is 55% complete.
Versión de MediaWiki:
1.25
Gerrit change 187728

A partir de MediaWiki 1.25 , MediaWiki puede generar contenido en HTML a partir de plantillas de Mustache al servidor y el cliente. Server-side template parsing is implemented in PHP via the TemplateParser class, which acts as a wrapper around the lightncandy library. Client-side templates are supported via mediawiki.template* ResourceLoader modules and the mustache.js library.

This is unrelated to the use of MediaWiki templates in wikitext (such as the {{MW file}} in this article). Templating here builds the HTML of a web page, not the wiki content within it.

Crear plantillas

Para usar plantillas HTML en tu código, primero crea una plantilla de Mustache con la extensión .mustache, por ejemplo, MyWidget.mustache. Las plantillas tienen que contener la menor programación lógica posible, haciéndola fácil de leer y proporcinoando separación de intereses. Si tu plantilla forma parte del núcleo del software MediaWiki, colócala en el directorio includes/templates. Si este es parte de una extensión, debes crear otro directorio templates dentro de la carpeta de dicha extensión para alojarlo. Las plantillas deben seguir la especificación de Mustache-5.

TemplateParser (lado del cliente)

Before MW 1.40.1:

Esta clase busca archivos de plantillas, los lee, los compila dentro del código PHP y expande etiquetas a la plantilla usando datos que proporciones para producir el producto HTML. MediaWiki compila las plantillas cuando sea necesario, y utiliza la caché para almacenar las plantillas compiladas si están disponibles (véase #Caché más abajo). Esto evita que los desarrolladores tengan que compilar las plantillas en archivos PHP durante el desarrollo o como paso de compilación, o que el servidor los escriba al sistema de archivos durante la operación.

Para usar TemplateParser, primero crea una nueva instancia de la clase:

$templateParser = new TemplateParser();

If your Mustache templates do not reside in core's includes/templates, you need to pass the path to where they reside as the first parameter to the constructor (either relative to your MediaWiki root or relative to the calling file's directory with __DIR__):

$templateParser = new TemplateParser(  __DIR__ . '/templates' );

Luego tiene que analizar las plantillas en HTML llamando la función processTemplate(). El primer parámetro es el nombre de tu plantilla (la parte del nombre de archivo antes de .mustache). El segundo es un array que proporciona los valores necesarios por las etiquetas Mustache en tu plantilla. Por ejemplo:

echo $templateParser->processTemplate(
    'MyWidget',
    [
        'username' => $user->getName(),
        'message' => 'Hello!'
    ]
);

Esto reemplaza cualquier instancia de las etiquetas {{username}} y {{message}} en la plantilla mustache "MyWidget" con los valores que proporcionaste, y devuelve el código HTML resultante. (echo solamente imprime el código HTML generado en el contexto de salida actual)

Para un ejemplo de plantillas HTML, véase includes/templates/NoLocalSettings.mustache siendo usado por includes/NoLocalSettings.php.

Caché

TemplateParser intenta almacenar en caché la plantilla en PHP compilada. It prefers to use CACHE_ACCEL (See Manual:APC ), but falls back to CACHE_ANYTHING (a general object cache like Memcached or Redis, see Manual:Caching ).

CACHE_ACCEL requires the "apc" extension in PHP 5.4 or earlier, and the "apcu" extension for PHP 5.5+. HHVM has it built-in.

Partials

The cache is keyed on a hash of the template file's contents, so if you change a template file, the compiled template will update (you may need to clear your wiki's front-end cache using ?action=purge). However, this does not notice changes to "partial" templates that you include with {{>SubTemplateName}} (bug T113095). So if you change a partial, you need to make cosmetic changes to the parent templates that include it, or restart your cache.


mw.template (lado del cliente)

To use a Mustache template on the client-side, add it to your ResourceLoader module definition first:

'ext.coolExtension.interface' => [
	'templates' => [
		'foo.mustache' => 'templates/foo.mustache',
	],
	'scripts' => [
		'resources/interface.js',
	],
],

The template definition above consists of two pieces, a file path (templates/foo.mustache) and an optional alias (foo.mustache). The alias must be suffixed with the name of the templating language (e.g. '.mustache') so that it knows which compiler to use. ResourceLoader automatically serves the supporting mediawiki.template.xx JavaScript modules, so you don't need to mention anything in dependencies. Once you have added the template to your module, you can retrieve it in JavaScript using mw.template.get():

myTemplate = mw.template.get( 'ext.coolExtension.interface', 'foo.mustache' );

To render the template and data into HTML output, call the compiled template's render() function:

data = {
	username: mw.config.get( 'wgUserName' ),
	message: 'Hello!'
};
$html = myTemplate.render( data );

Partials

Versión de MediaWiki:
1.27
Gerrit change 206490

Partials are also supported on the client-side. See https://mustache.github.io/mustache.5.html#Partials for more information.

Véase también