Розширення:TemplateStyles

This page is a translated version of the page Extension:TemplateStyles and the translation is 40% complete.
Довідка про розширення MediaWiki
TemplateStyles
Статус релізу: стабільний
Реалізація Тег , ContentHandler , Хук
Опис Завантажує оздоровлені таблиці стилів CSS із шаблону.
Автор(и)
Найновіша версія Постійні оновлення
Compatibility policy Snapshots releases along with MediaWiki. Master is not backward compatible.
MediaWiki 1.30+
PHP 7.3+
Ліцензія GNU General Public License 2.0 or later
Завантажити
  • $wgTemplateStylesUseCodeEditor
  • $wgTemplateStylesDisable
  • $wgTemplateStylesDefaultNamespace
  • $wgTemplateStylesDisallowedAtRules
  • $wgTemplateStylesDisallowedProperties
  • $wgTemplateStylesAllowedUrls
  • $wgTemplateStylesAutoParseContent
  • $wgTemplateStylesMaxStylesheetSize
  • $wgTemplateStylesNamespaces
<templatestyles src=... />
Quarterly downloads 1,021 (Ranked 1st)
Public wikis using 1,977 (Ranked 199th)
Translate the TemplateStyles extension if it is available at translatewiki.net
Issues Open tasks · Report a bug

TemplateStyles — розширення парсера, що дозволяє користувачам зберігати замовний код CSS на вікі-сторінках і вбудовувати ці стилі у статті через тег ‎<templatestyles>. Розширення дозволяє зберігання тільки безпечної підмножини синтаксису CSS у вбудовуваних сторінках стилів. Воно працює на бібліотеці css-sanitizer.

Дописувачів заохочують включати стилі шаблонів через TemplateStyles, оскільки це дозволяє тим самим користувачам редагувати і шаблон, і його стилі, а також такі стилі завантажуються лише за необхідності (порівняно з додаванням до загального для сайту MediaWiki:Common.css ).

Інструкції з використання розширення дописувачем вікіпедії див. на Help:TemplateStyles .

Використання

Спочатку потрібно створити сторінку CSS. Усталено, будь-яка підсторінка у просторі «Шаблон», назва якої закінчується на «.css», буде створена з «Очищений CSS» content model , якщо вона не містить синтаксичних помилок.

Множину просторів можна доповнити $wgTemplateStylesNamespaces, або використати Special:ChangeContentModel на будь-якій сторінці. Потім, у вікітексті шаблону, додайте тег <templatestyles src="..." /> для завантаження стилів.

CSS, збережені з використанням моделі вмісту «Очищений CSS», повинні відповідати суворим вимогам дійсності: недійсні CSS, нерозпізнані at-правила, а також нерозпізнані чи непідтримувані властивості чи їх значення не можуть бути збережені. Якщо недійсний CSS так чи інакше був збережений, то несправні конструкції будуть вилучені під час виведення CSS у браузер.

Значенням атрибуту src в тега є назва сторінки, усталено у просторі «Шаблон». (це усталення можна змінити через $wgTemplateStylesDefaultNamespace) Наприклад, <templatestyles src="Example/styles.css" /> завантажить сторінку «Template:Example/styles.css». Це не вийде, якщо така сторінка не існує або її модель вмісту не є «Очищений CSS».

Стилі можуть бути осягнуті на сторінку використанням опційного параметру тега wrapper, наприклад, <templatestyles src="Example/styles.css" wrapper="div.example" /> осягне стилі, завантажені до будь-якого <div class="example"> усередині основного вмісту. Будь-яку просту послідовність селекторів CSS можна використати для параметра wrapper. Це призначено для порівняння пліч-о-пліч живої та пісочної версій шаблону.

Використання оздоровлених CSS відстежується як включення шаблонів і показуватиметься як включення на Special:WhatLinksHere .

Застереження

  • Styles added by TemplateStyles are scoped into .mw-parser-output to avoid tampering with the user interface outside of the main parsed content.
    • To use TemplateStyles to style something like w:MediaWiki:Protectedpagetext, you would need to enclose the message's contents in <div class="mw-parser-output">...</div>.
  • The styles should be written to target specific CSS classes, and anything that generates elements with those classes should also be sure to include the styles themselves rather than relying on some other template to do so.
    • Styles included by a template can currently affect content on the page outside of the content generated by that template, but this ability may be removed in the future and should not be relied upon.

(See discussion from phab:T155813#2996589 and in phab:T176272.)

    • Including styles on a template that affects contents outside of that template will cause those styles not to be applied when editing a section that doesn't contain that template. Example: including styles on an info box that affect all tables of the page, when editing a section that doesn't contain the infobox, those tables won't be styled when previewing that section.
  • TemplateStyles does not support CSS variables, see phab:T320322.
  • TemplateStyles allows a few non-standardized CSS properties.

Requests to support additional properties should be filed in Phabricator in the css-sanitizer and TemplateStyles projects.

    • Requests should include links to standards-track documents (e.g., on w3.org) describing the syntax of the properties being requested and an analysis of current browser support for the properties (e.g., a link to a caniuse.com page about the properties).
    • Vendor-prefixed properties (e.g. anything starting with -webkit-, -moz-, or -ms-) are likely to be declined if they're not needed for modern browsers.
  • @font-face rules must use a font-family prefixed with "TemplateStyles".

This should largely prevent redefining fonts used elsewhere in the document.

  • To target styles based on skins, use a selector such as body.skin-vector .myClass; specification of the body element is required and must be followed by a descendant combinator (i.e. the space).

Other classes on the body or html elements may be targeted in the same manner. See phab:T197617. 1.32+

Встановлення

  • Завантажте і розмістіть файли в каталозі з назвою TemplateStyles у вашій extensions/ папці.
    Розробники та автори коду повинні замість цього встановити розширення з Git, використовуючи:cd extensions/
    git clone https://gerrit.wikimedia.org/r/mediawiki/extensions/TemplateStyles
  • Тільки під час встановлення з git виконайте Composer для встановлення залежностей PHP, подаючи composer install --no-dev в каталозі розширень. (Див. завдання T173141 щодо можливих ускладнень.)
  • Додайте такий код унизу вашого файлу LocalSettings.php :
    wfLoadExtension( 'TemplateStyles' );
    
  • Налаштуйте як вимагається.
  •   Готово – Перейдіть до Special:Version вашої вікі, щоб переконатися, що розширення встановлено успішно.


Встановлення з Vagrant:

  • Якщо використовується Vagrant , встановіть з vagrant roles enable templatestyles --provision
For a more pleasant user interface, with syntax highlighting and a code editor with autoindent, install the following extensions:

Конфігурація

Configuration settings
параметр усталене коментар
$wgTemplateStylesAllowedUrls
[
    "audio" => [
        "<^https://upload\\.wikimedia\\.org/wikipedia/commons/>"
    ],
    "image" => [
        "<^https://upload\\.wikimedia\\.org/wikipedia/commons/>"
    ],
    "svg" => [
        "<^https://upload\\.wikimedia\\.org/wikipedia/commons/[^?#]*\\.svg(?:[?#]|$)>"
    ],
    "font" => [],
    "namespace" => [
        "<.>"
    ],
]
PCRE regular expressions to match allowed URLs for various types of external references.

Keys are external reference types, and values are arrays of regular expressions (including delimiters) to match allowed URLs. Current external reference types are:

audio
Sound file, for cue properties of the CSS Speech Module.
image
Image file, for properties such as background.
svg
SVG file, for Masking and Filters.
font
For @font-face's src.
namespace
For @namespace.
$wgTemplateStylesNamespaces [ NS_TEMPLATE => true ] Namespaces in which to set the "Очищений CSS" content model for titles ending in ".css".

Enabling this for 2 (User) or 8 (MediaWiki) is a bad idea, as it will conflict with the normal CSS files in those namespaces.

$wgTemplateStylesPropertyBlacklist [] Properties to blacklist in CSS style rules.

The TemplateStylesPropertySanitizer hook allows for finer-grained control.

$wgTemplateStylesAtRuleBlacklist [] At-rules to blacklist in stylesheets.

The TemplateStylesStylesheetSanitizer hook allows for finer-grained control.

$wgTemplateStylesUseCodeEditor true Whether to enable Extension:CodeEditor for the "Очищений CSS" content type.
$wgTemplateStylesAutoParseContent true If true, the "Очищений CSS" content model will be added to $wgTextModelsToParse if the CSS content model is already present in that array.

If false, add 'sanitized-css' to that array manually if you want categories and such parsed out of the CSS page.

$wgTemplateStylesMaxStylesheetSize 102400 Maximum size (in bytes) of a stylesheet. null for no limit.
$wgTemplateStylesDefaultNamespace NS_TEMPLATE The default namespace for the src attribute of the ‎<templatestyles> tag.

Інші залежності

$wgTidyConfig should be configured to use no tidying or RemexHtml. If used with any of the Raggett drivers, a ‎<templatestyles /> tag in the middle of a paragraph (including in an inline template) will cause tidy to break the paragraph at that point. The other drivers have not been tested for this issue.

Потенційні помилки

It may help to enable $wgShowExceptionDetails in your LocalSettings.php to determine if you are experiencing any of the errors below.

  • Class 'Wikimedia\CSS\Parser\Parser' not found
    This means a required library has not been installed. The error may come up when attempting to import a wiki CSS page or when changing the content model of a page to "sanitized-css". This was common in the past due to a bug in the extension distributor; shouldn't happen anymore.
  • Import failed: The content model 'sanitized-css' is not registered on this wiki.
    Happens when you try to import a wiki page created via TemplateStyles, but TemplateStyles is not installed on your wiki.

Див. також