Руководство:HTML шаблоны
Версия MediaWiki: | ≥ 1.25 Gerrit change 187728 |
Начиная с MediaWiki 1.25 , MediaWiki может генерировать HTML-контент из шаблонов Mustache на сервере и на клиенте.
Разбор шаблонов на стороне сервера реализован в PHP через класс TemplateParser, который действует как оболочка для библиотеки lightncandy.
Разбор клиентских шаблонов поддерживаются с помощью mediawiki.template*
модуля ResourceLoader и библиотеки mustache.js
.
Creating templates
To use HTML templates in your code, first create a Mustache template file with a .mustache
file extension, for example, MyWidget.mustache
.
Templates should contain as little programming logic as possible so that they are easily readable and provide proper separation of concerns.
If your template is part of the core MediaWiki software, put it in core's includes/templates
directory.
If it is part of an extension, you should create a dedicated templates
directory within your extension's directory to hold it.
Templates should follow the Mustache-5 specification.
TemplateParser (server-side)
Файл MediaWiki: TemplateParser.php | |
---|---|
Расположение: | includes/Html/ |
Исходный код: | master • 1.42.3 • 1.41.4 • 1.39.10 |
Классы: | TemplateParser |
Before MW 1.40.1:
Файл MediaWiki: TemplateParser.php | |
---|---|
Расположение: | includes/ |
Исходный код: | master • 1.42.3 • 1.41.4 • 1.39.10 |
Классы: | TemplateParser |
This class finds template files, reads them, compiles them into PHP code, and expands tags in the template using data you provide to produce the output HTML. MediaWiki compiles templates as needed, and uses caching to store the compiled templates if available (see #Caching below). This avoids developers having to compile templates into PHP files during development or as a build step, or the server writing them to the file system during operation.
To use TemplateParser
, first create a new instance of the class:
$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' );
You then parse templates into HTML by invoking the processTemplate()
function.
The first parameter to this is the name of your template (the part of the filename before .mustache
).
The second parameter is an array providing the values needed by the Mustache tags in your template.
For example,
echo $templateParser->processTemplate(
'MyWidget',
[
'username' => $user->getName(),
'message' => 'Hello!'
]
);
This replaces any instances of {{username}}
and {{message}}
tags in the "MyWidget" mustache template with the values you provided, and returns the resulting HTML.
(The echo
simply prints the generated HTML in the current output context.)
As an example of HTML templating, see includes/templates/NoLocalSettings.mustache as used by includes/Output/NoLocalSettings.php.
Caching
TemplateParser attempts to cache the compiled PHP template.
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 ).
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 (client-side)
To use a Mustache template on the client-side, add it to your Загрузчик ресурсов 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
Версия 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.
См. также
- Руководство:SkinMustache.php
- Руководство:Как создать тему оформления MediaWiki
- Skins:
- Extensions:
- Extension:SemanticMustacheFormat (unmaintained)
- Extension:Mustache i18n (unmaintained)
- Requests for comment/HTML templating library (closed)