Статус релиза: стабильно | |
|---|---|
| Реализация | Тег,Функция парсера,Служебная страница |
| Описание | Обеспечивает динамическое представление о структуре категорий вики в виде дерева. |
| Автор(ы) | Daniel Kinzler (Duesentriebобсуждение) |
| Последняя версия | постоянно обновляется |
| Политика совместимости | Снэпшоты выходят вместе с MediaWiki. Мастер не имеет обратной совместимости. |
| MediaWiki | 1.25+ |
| Лицензия | GNU General Public License 2.0 или позднее |
| Скачать | README |
| |
| Переведите расширение CategoryTree, если оно доступно на translatewiki.net | |
| Проблемы | Открытые задачи ·Сообщить об ошибке |
РасширениеCategoryTree обеспечивает динамическое представление о структуре категорий в вики в виде дерева. Он используетAJAX для загрузки части дерева по требованию. CategoryTree был первоначально написан Даниэлем Кинзлером (Daniel Kinzler) как внешний инструмент. Позже это расширение было интегрировано в программное обеспечение MediaWiki с помощью Тима Старлинга (Tim Starling).
CategoryTree в вашей папкеextensions/.cdextensions/gitclonehttps://gerrit.wikimedia.org/r/mediawiki/extensions/CategoryTreewfLoadExtension('CategoryTree');
CategoryTree может быть использован тремя путями:
Расширение CategoryTree добавляет виджет►, который "разворачивает" подкатегории, перечисленные на страницах категории.
Пример. Результат можно увидеть в поле ниже и справа:
<categorytreemode="pages">Manual</categorytree>
Пользовательский тег называется<categorytree>. Например, если вы поместите $code на вики-странице, он отобразит содержимое категории Foo как динамическое дерево на странице (см. пример справа). Тег принимает следующие атрибуты, используя HTML-подобный синтаксис:For example, if you put <categorytree>Foo</categorytree> on a wiki page, it will show the contents of category Foo as a dynamic tree on that page (see example to the right).The tag accepts the following attributes, using a HTML-like syntax:
namespaces. Возможные значения:0)10)20)100). Это помещает CategoryTree в "инверсивную" операцию (поддерживается начиная сr36892, июль 2008).$wgCategoryTreeMaxDepth. (введено междуr20410 иr20840, 30 марта 2007; полностью функциональна даже с$wgCategoryTreeDynamicTag начиная сr36864, июль 2008)depth="0".(введено вr20385, 13 марта 2007)depth="0".hideroot=on. Например, он не будет отображать название категории Foo10).0).mode="categories" (константа30); Это эквивалентно старому поведению по умолчанию (до июня 2008).20). Это новое поведение по умолчанию (начиная сr36864, июль 2008).showcount="on" (начиная сr36864, июль 2008). По умолчанию отключено для встроенного в страницы дерева категорий, но включено по умолчанию в списках категорий и на Special:CategoryTree.notranslations="on" (начиная сGerrit change 526234, ноябрь 2019). Это по умолчанию отключено. Если для этого параметра установлено значение «on», вместо различных переводов (например, «Страница», «Страница/en», «Страница/fr», «Страница/de») отображается только стандартный перевод «Страница», а все остальные переводы подавляются.<categorytree> поддерживает все стандартные HTML-атрибуты блока элементов (начиная сr36864, июль 2008; до этого был поддержан толькоstyle).Категория — это пространство имён. Категории по умолчанию отображаются во всех режимах, но при указании параметра $param они скрываются, как и любое другое пространство имён, отсутствующее в списке. Если вы хотите отобразить страницы в заданном пространстве имён, включая страницы в подкатегориях, просто добавьте «Категория» (Category) в список пространств имён.Categories are shown in all modes by default, but specifying thenamespaces parameter hides them just like any other namespace not present on the list.If you want to list pages in a given namespace, including pages in subcategories, simply add Category to the namespace list.
Пример:
<categorytreemode="pages"namespaces="Main">Manual</categorytree>
<categorytreemode="pages"namespaces="Main Category">Manual</categorytree>
Параметрmode переопределяется параметромnamespaces:
mode=categories;mode=all;mode=pages. Это означает, что если конфигурация сайта не была изменена, то следующие варианты эквивалентны (первые два всегда эквивалентны, третий — только если$wgCategoryTreeDefaultMode является константойCategoryTreeMode::CATEGORIES по умолчанию):<categorytreemode="categories">Manual</categorytree><categorytreenamespaces="Category">Manual</categorytree><categorytree>Manual</categorytree>
Начиная сr25825 (2007-9-13), вы можете также использовать синтаксисфункций парсера чтобы поместить дерево категорий на странице. Работает подобно тегу <categorytree>, используя другой синтаксис, например,{{#categorytree:Foo}}; опции могут быть определены с использованием синтаксиса именованных параметров шаблона, например,{{#categorytree:Foo|hideroot|mode=pages}}.
Использование синтаксиса функций парсера имеет преимущество, позволяющее использовать волшебные слова, шаблоны и параметры шаблонов при определении категории для отображения. Вот некоторые примеры:
{{#categorytree:{{PAGENAME}}}}.{{#categorytree:{{root category}}}} - имя корневой категории будут определены по содержанию Template:Root_category.{{#categorytree:{{{1}}}}} в Template:Baz может вызываться при помощи {{Baz|Foo}}Служебная страница называется Special:CategoryTree; здесь вы можете ввести название категории, а затем просмотреть её содержание.
Существуют некоторые опции, которые вы можете указать в своем файлеLocalSettings.php:
0 для режима категорий,10 для страниц,20 для всех,100 для родителей.$wgCategoryTreeDefaultOptions['hideprefix'] instead.$wgCategoryTreeMaxDepth=[10=>2,20=>2,0=>3,100=>2];.0 (the default - categories),10 (pages), or20 (all).$wgCategoryTreeCategoryPageOptions['mode'] instead.$wgCategoryTreeDefaultOptions['mode']='pages';.By default, when listing subcategories on a category page, each subcategory is followed by an integer, indicating how many subcategories lie beneath it, how many pages it contains, and how many files are in the category (if applicable):
You can change this behavior by overriding the system messageMediaWiki:Categorytree-member-num. It takes five parameters:
| Parameter | Meaning |
|---|---|
| $1 | Number of subcategories |
| $2 | Number of articles (not including category pages or file pages) |
| $3 | Number of uploaded files |
| $4 | Total number of member pages, including category pages and file pages |
| $5 | Something close to ($1 C, $2 P, $3 F) but with anything that is 0 omitted. More precisely, a comma separated list of the number of pages (mediawiki:categorytree-num-pages), subcategories (mediawiki:categorytree-num-categories), and files (mediawiki:categorytree-num-files) in the category, or empty (mediawiki:categorytree-num-empty) in the case the category has no members. In versions prior to those around 1.19 this value was different. Seeolder version of these docs. |
The default value is($5).
Tip: Use theParserFunctions extension to provide if/then/else logic to display different parts conditionally. For example:
{{#ifeq:$1|0||$1 categories}}A configuration to manage commas and spaces when outputting all info:
Abbreviation version:
({{#ifeq:$4|0|empty|{{#ifeq:$1|0||$1 C{{#ifeq:{{#expr:$3+$2}}|0||,}}}} {{#ifeq:$2|0||$2 P{{#ifeq:$3|0||,}}}} {{#ifeq:$3|0||$3 F}}}})Full name version:
({{#ifeq:$4|0|empty|{{#ifeq:$1|0||$1 categories{{#ifeq:{{#expr:$3+$2}}|0||,}}}} {{#ifeq:$2|0||$2 pages{{#ifeq:$3|0||,}}}} {{#ifeq:$3|0||$3 files}}}})$wgUseAjax=true; in your LocalSettings.phpbefore including the extension.$wgCategoryTreeDefaultOptions['namespaces']=[0,NS_CATEGORY,NS_FILE];Since MediaWiki 1.13, CategoryTree can show the number of members of a category, and can show a grey arrow► for tree nodes that do not have any children based on that number. This information is based on the newcategory table. However, populating that table with the current values does not always work when upgrading to 1.13. In that case, run thepopulateCategory.php maintenance script, if necessary with the--force option.
In case you get only one level depth while visualing the tree, try to set in modules/ext.categoryTree.styles.css filedisplay:none; todisplay:inline!important;.
The JavaScript intended to switch the tag style is somehow buggy.
Bots and scripts that parse the HTML of category pages can use thenotree URL parameter to force the traditional output. However, HTML output is generally not stable, so it is recommended to change your script to use theAPI to fetch category listings and similar.
After you implement the CategoryTree plugin and add the code to show the tree, if you see a message that saysCategory Not Found, you need to add some content in your category pages. The category pages can't be red pages, basically. Click your category names, add some text in the category page, and then your tree should work fine.
Make sure the right version of this extension is installed, relative to the version of MediaWiki you have installed. In particular, versions of this extension made for versions of MediaWiki prior to 1.17 are not compatible with MediaWiki 1.17 and greater, and will cause issues where all the paging links on category pages are broken.
Seeabove.
In older versions of CategoryTree, you have to modify the code to make this work: find theefCategoryTreeParserOutput function in the file CategoryTree.php, and remove the condition; i.e. it should then look like this:
functionefCategoryTreeParserOutput(&$outputPage,&$parserOutput){CategoryTree::setHeaders($outputPage);returntrue;}
Sincer36920 (July 2008) with MediaWiki 1.13 (r36917), you can integrate a CategoryTree in the sidebar simply by setting$wgCategoryTreeSidebarRoot to the category you want to use as a root. This only works with skins based upon SkinTemplate however, that is, Modern, Monobook, Chick, Simple, and MySkin, but not Standard, Nostalgia or CologneBlue.
If you want the CategoryTree on a different position in the sidebar, you can reference it onMediaWiki:Sidebar as "categorytree-portlet".
For earlier versions of CategoryTree and/or MediaWiki, you'll need to install a mod to MonoBook.php to enable normal wikitext in the sidebar, seeWikitext in side bar --DJ 19:26, 24 January 2008 (UTC)
To append a link "CategoryTree" to your toolbox (sidebar) add following code to the JavaScript page (e.g.monobook.js) of yourskin and customize the URL "w:Special:CategoryTree".
functionAppendCategoryTreeToSidebar(){try{varnode=document.getElementById("p-tb").getElementsByTagName('div')[0].getElementsByTagName('ul')[0];varaNode=document.createElement('a');varliNode=document.createElement('li');aNode.appendChild(document.createTextNode('CategoryTree'));aNode.setAttribute('href','[[w:Special:CategoryTree]]');liNode.appendChild(aNode);liNode.className='plainlinks';node.appendChild(liNode);}catch(e){// lets just ignore what's happenedreturn;}}addOnloadHook(AppendCategoryTreeToSidebar);
A more generic version of this code can be found atManual:Interface/Sidebar#content of sidebar and toolbox (javascript).
Step by step if works easy:
$wgCategoryTreeSidebarRoot='Category:article_name';
If you want to create a link that goes to the generic categorytree (displayed asCategory tree) when you're on a non-category page, and to a particular categorytree (displayed asView as category tree, with foo being the name of the category you're viewing) when you're on a category page:
** sidebarcategorytree-url|sidebarcategorytree{{#ifeq: {{NAMESPACE}}|Category|View as category tree|Category tree}}{{#ifeq: {{NAMESPACE}}|Category|Special:CategoryTree/{{BASEPAGENAME}}|Special:CategoryTree/Categories}}| Это расширение используется в одном или несколькихпроектах Викимедиа. Вероятно, это означает, что расширение стабильно и работает достаточно хорошо, чтобы использоваться такими сайтами с высоким трафиком. Найдите название этого расширения в файлах конфигурации ВикимедиаCommonSettings.php иInitialiseSettings.php, чтобы узнать, где оно установлено. Полный список расширений, установленных на конкретной вики, можно увидеть на страницеSpecial:Version wiki. |
| Это расширение включено в следующие вики-фермы/хостинги и/или пакеты: |