Расширение:Дерево категорий

From mediawiki.org
This page is a translated version of the page Extension:CategoryTree and the translation is 31% complete.
Outdated translations are marked like this.
Это расширение поставляется с MediaWiki 1.31 и выше. Таким образом, вам не нужно загружать его снова. Тем не менее, вы всё равно должны следовать другим инструкциям.
Справка по расширениям MediaWiki
CategoryTree
Статус релиза: стабильно
Реализация Тег , Функция парсера , Служебная страница
Описание Обеспечивает динамическое представление о структуре категорий вики в виде дерева.
Автор(ы) Daniel Kinzler (Duesentriebобсуждение)
Последняя версия continuous updates
Политика совместимости Snapshots releases along with MediaWiki. Master is not backward compatible.
MediaWiki 1.25+
Лицензия GNU General Public License 2.0 или позднее
Скачать
README
  • $wgCategoryTreeAllowTag
  • $wgCategoryTreeCategoryPageOptions
  • $wgCategoryTreePageCategoryOptions
  • $wgCategoryTreeMaxDepth
  • $wgCategoryTreeSidebarOptions
  • $wgCategoryTreeDefaultOptions
  • $wgCategoryTreeMaxChildren
  • $wgCategoryTreeSpecialPageOptions
  • $wgCategoryTreeOmitNamespace
  • $wgCategoryTreeSidebarRoot
  • $wgCategoryTreeDisableCache
  • $wgCategoryTreeCategoryPageMode
  • $wgCategoryTreeDefaultMode
  • $wgCategoryTreeUseCategoryTable
  • $wgCategoryTreeHijackPageCategories
Ежеквартальные загрузки 346 (Ranked 15th)
Использование общедоступными вики 10,554 (Ranked 11th)
Переведите расширение CategoryTree, если оно доступно на translatewiki.net
Проблемы Открытые задачи · Сообщить об ошибке

Расширение CategoryTree обеспечивает динамическое представление о структуре категорий в вики в виде дерева. Он использует AJAX для загрузки части дерева по требованию. CategoryTree был первоначально написан Даниэлем Кинзлером как внешний инструмент. Позже это расширение было интегрировано в программное обеспечение MediaWiki с помощью Тима Старлинга.

Установка CategoryTree

  • Скачайте и распакуйте файл(ы) в папку с названием CategoryTree в вашей папке extensions/.
    Вместо этого разработчикам и соавторам кода следует установить расширение из Git, используя:cd extensions/
    git clone https://gerrit.wikimedia.org/r/mediawiki/extensions/CategoryTree
  • Добавьте следующий код в конце вашего файла LocalSettings.php :
    wfLoadExtension( 'CategoryTree' );
    
  • Yes Готово – Перейдите на страницу Special:Version на своей вики, чтобы удостовериться в том, что расширение успешно установлено.

Использование

CategoryTree может быть использован тремя путями:

  • непосредственно на страницах категорий,
  • как "пользовательский тег" (или "функция парсера") для отображения структуры категории построчно на вики,
  • а также на специальной странице.

Расширение CategoryTree добавляет виджет , который "разворачивает" подкатегории, перечисленные на страницах категории.

Тег <categorytree>

Example. The result can be seen in the box below and on the right:

<categorytree mode="pages">Manual</categorytree>

Пользовательский тег называется <categorytree>. Например, если вы поместите <categorytree>Foo</categorytree> на вики-странице, он отобразит содержимое категории Foo как динамическое дерево на странице (см. пример справа). Тег принимает следующие атрибуты, используя HTML-подобный синтаксис:

mode
определяет, какие страницы будут отображены в дереве. Может быть изменено с помощью namespaces. Возможные значения:
categories
показывать только подкатегории (константа 0)
pages
показывать подкатегории и страниц, без изображений (константа 10)
all
показывать все подкатегории, страницы, картинки и т.д. (константа 20)
parents
список корневых категорий, а не подкатегории (константа 100). Это помещает CategoryTree в "инверсивную" операцию (поддерживается начиная с r36892, июль 2008).
depth
определяет, сколько показывать уровней дерева на начальном этапе. По умолчанию 1. 0 означает, только корневой узел. Максимальное значение зависит от указанного режима, и в опции $wgCategoryTreeMaxDepth. (введено между r20410 и r20840, 30 марта 2007; полностью функциональна даже с $wgCategoryTreeDynamicTag начиная с r36864, июль 2008)
onlyroot
"on" показывает только "корневой" узел дерева на начальном этапе. Эквивалент depth="0". (введено в r20385, 13 марта 2007). Запрещено в r36864, июль 2008: заместо него использовать depth="0".
hideroot
"on" спрячет "корневой" узел дерева, т. е. hideroot=on. Например, он не будет отображать название категории Foo
hideprefix
определяет, когда префикс пространства имён должны быть скрыт от записи в дереве (начиная с r36864, июль 2008). Возможные значения:
always
всегда скрывать префикс. Следует использовать только тогда, когда все страницы имеют одно и то же пространство имён (константа 10).
never
никогда не скрывать префикс (константа 0).
auto
скрывать пространство имён категорий, если категории показаны через mode="categories" (константа 30); Это эквивалентно старому поведению по умолчанию (до июня 2008).
categories
всегда скрывать пространство имен категорий, но показать все другие префиксы (константа 20). Это новое поведение по умолчанию (начиная с r36864, июль 2008).
showcount
"on", чтобы показать число записей в подкатегории, т. е. showcount="on" (начиная с r36864, июль 2008). По-умолчанию отключено для дерева категории встроенного в страницы, но по-умолчанию включено в списках категорий на страница Служебная:CategoryTree. This is disabled per default for category trees inlined on pages, but enabled per default in category listings and on Special:CategoryTree.
notranslations
set this to "on" to hide all translations pages corresponding to the pages pertaining to the category, i.e. notranslations="on" (since Gerrit change 526234, November 2019). This is disabled by default. If this option is set to "on", instead of the different translations (e.g. Page, Page/en, Page/fr, Page/de) only the standard translation "Page" is displayed and all translations are suppressed.
This doesn't affect "showcount", so still a bug.
namespaces
список пространств имён страниц, которые должно быть показано в дереве (начиная с r36864, июль 2008). Записи в списке должны быть разделены пробелами. Основное пространство имён может быть представлено как "-" или "0".
class, style, id, etc
тег <categorytree> поддерживает все стандартные HTML-атрибуты блока элементов (начиная с r36864, июль 2008. До этого был поддержан только style).

Notes on the 'namespaces' parameter

Category is a namespace. Categories are shown in all modes by default, but specifying the namespaces 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.

Example:

  • Listing main namespace pages in Category:Manual:
<categorytree mode="pages" namespaces="Main">Manual</categorytree>
  • Listing main namespace pages and subcategories in Category:Manual:
<categorytree mode="pages" namespaces="Main Category">Manual</categorytree>

The mode parameter is overridden by namespaces:

  • if only Category namespace is asked, it's equivalent to mode=categories;
  • if file namespace is present on the list, it will imply mode=all;
  • otherwise mode=pages will be used. It means that if the site configuration hasn't been changed, the following are equivalent (the first two are always equivalent, the third only if $wgCategoryTreeDefaultMode is the default CategoryTreeMode::CATEGORIES):
<categorytree mode="categories">Manual</categorytree>
<categorytree namespaces="Category">Manual</categorytree>
<categorytree>Manual</categorytree>

Синтаксический анализатор {{#categorytree}}

Начиная с r25825 (2007-9-13), вы можете также использовать синтаксис синтаксического анализатора чтобы поместить дерево категорий на странице. Работает подобно тегу <categorytree>, используя другой синтаксис, например, {{#categorytree:Foo}}; опции могут быть определены с использованием синтаксиса именованных параметров шаблона, например, {{#categorytree:Foo|hideroot|mode=pages}}.

Использование синтаксиса синтаксического анализатора имеет преимущество, позволяющее использовать волшебные слова, шаблоны и параметры шаблонов при определении категории для отображения. Вот некоторые примеры:

  • Использование волшебной переменной для отображения этих страниц дерева категорий (могут быть полезны на страницах описания категории): {{#categorytree:{{PAGENAME}}}}.
  • Использование шаблонов для указания категории: {{#categorytree:{{root category}}}} - имя корневой категории будут определены по содержанию Template:Root_category.
  • Использование шаблонов для указания категории, при использовании CategoryTree внутри шаблона: {{#categorytree:{{{1}}}}} в Template:Baz может вызываться при помощи {{Baz|Foo}}

Страница Special:CategoryTree

Специальные страницы, называется Special:CategoryTree, здесь вы можете ввести название категории, а затем просмотреть его содержание.

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

Существуют некоторые опции, который вы можете указать в своем файле LocalSettings.php :

You can no longer use CT_* constants in LocalSettings.php. Instead use 0 for category mode, 10 for pages, 20 for all, 100 for parents.
$wgCategoryTreeMaxChildren
максимальное количество дочерних категорий в дереве. По умолчанию 200.
$wgCategoryTreeAllowTag
включить тег <categorytree>. По умолчанию true.
$wgCategoryTreeDynamicTag
загрузка первого уровня в дерево <categorytree> динамически. Таким образом, кэширование не должно быть отключено. По умолчанию false.
$wgCategoryTreeDisableCache
отключить кэширование для страниц с тегом <categorytree>. По умолчанию 21600, что составляет 6 часов.
$wgCategoryTreeUseCache
enable HTTP cache for anon users. Default is false.
$wgCategoryTreeOmitNamespace
do not show the namespace name for pages and categories. Default is false, namespaces are shown unless showing categories only. Deprecated as of r36864, July 2008: use $wgCategoryTreeDefaultOptions['hideprefix'] instead.
$wgCategoryTreeMaxDepth
an array defining the maximum depth for each mode, to which the tree may be expanded initially using the depth parameter in a <category> tag. By default, this is set to 2 for the "categories" mode, and 1 for other modes. To set it to 3 for categories and 2 for other modes, for example, you can use $wgCategoryTreeMaxDepth = [10 => 2, 20 => 2, 0 => 3, 100 => 2];.
$wgCategoryTreeDefaultMode
the default mode to use when no mode attribute is specified in a <categorytree> tag. May be 0 (the default - categories), 10 (pages), or 20 (all).
$wgCategoryTreeCategoryPageMode
the mode to use when rendering trees on category pages. Deprecated as of r36864, July 2008: use $wgCategoryTreeCategoryPageOptions['mode'] instead.
$wgCategoryTreeSidebarRoot
root category to use for integrating the category tree in the sidebar (since r36920, July 2008). If not set, no tree is integrated (this is the default). Integrating a CategoryTree into the sidebar only works with skins based upon SkinTemplate, that is, Modern, Monobook, Chick, Simple, and MySkin, but not Standard, Nostalgia or CologneBlue. This is currently broken for MediaWiki 1.35.1 and the vector skin, see phab:278306.
$wgCategoryTreeDefaultOptions
default options to apply, as an array (since r36864, July 2008). The available options are described above. Example: $wgCategoryTreeDefaultOptions['mode'] = 'pages';.
$wgCategoryTreeCategoryPageOptions
options to use on category pages, as an array (since r36864, July 2008).
$wgCategoryTreeSpecialPageOptions
options to use on Special:CategoryTree, as an array (since r36864, July 2008).
$wgCategoryTreeSidebarOptions
options to use when showing the tree in the sidebar, as an array (since r36920, July 2008)

System messages

categorytree-member-num

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):

My category name (5 C, 2 P, 1 F)

You can change this behavior by overriding the system message MediaWiki: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. See older version of these docs.

The default value is ($5).

Tip: Use the ParserFunctions 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}}}})

Поиск и устранение неисправностей

Wiki не работает после установки CategoryTree

  • Включите error reporting
  • Убедитесь, что установлены все необходимые файлы
  • Убедитесь, что все файлы расширения имеют правильно настроенные права доступа mode 644, и права на папку CategoryTree - 755.

Параметры в LocalSettings.php не дают эффекта

  • Убедитесь, что вы указываете параметры после подключения расширения.

Clicking the has no effect, gives a JavaScript error or just sits on loading

  • Note that using the <categorytree> tag in system messages (MediaWiki namespace) may not work as expected - this is a known caveat. For a workaround, see Using CategoryTree in the Sidebar below.
  • Make sure you have $wgUseAjax = true; in your LocalSettings.php before including the extension.
  • If you are using rewrite rules or aliasing (e.g. to have "very short URLs" - i.e. wiki pages in the document root or perhaps redirecting to a www-version of the requested URL), make sure you have an exception in place for the /extensions directory, just like you would for the /skins directory. Also see below.

Clicking the shows no sub-categories error

  • Try to fix this by adding this code to LocalSettings.php: $wgCategoryTreeDefaultOptions['namespaces'] = [ 0, NS_CATEGORY, NS_FILE ];

Browser reports a bad MIME type for CategoryTree.js and/or CategoryTree.css

  • Make sure your web server uses the correct MIME types for .js and .css files
  • Enter the URLs directly into the browser and see if it is serving the pages at all, and not some error page; especially:
  • If you are using rewrite rules or aliasing (e.g. to have "very short URLs" - i.e. wiki pages in the document root), make sure you have an exception in place for the /extensions directory, just like you would for the /skins directory.

Member counts are wrong, grey arrows are shown instead of

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 new category table. However, populating that table with the current values does not always work when upgrading to 1.13. In that case, run the populateCategory.php maintenance script, if necessary with the --force option.

toggles shown only on the first level of the category tree view

In case you get only one level depth while visualing the tree, try to set in modules/ext.categoryTree.styles.css file display: none; to display: inline !important;.

The JavaScript intended to switch the tag style is somehow buggy.

Note to bot users

Bots and scripts that parse the HTML of category pages can use the notree URL parameter to force the traditional output. However, HTML output is generally not stable, so it is recommended to change your script to use the API to fetch category listings and similar.

"Category Not Found" message

After you implement the CategoryTree plugin and add the code to show the tree, if you see a message that says Category 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.

Next 200 links do not work with CategoryTree installed

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.

No pages are shown when using the "namespaces" parameter

See above.

Hacks

Using CategoryTree in system messages and custom skins

In older versions of CategoryTree, you have to modify the code to make this work: find the efCategoryTreeParserOutput function in the file CategoryTree.php, and remove the condition; i.e. it should then look like this:

function efCategoryTreeParserOutput( &$outputPage, &$parserOutput )  {
    CategoryTree::setHeaders( $outputPage );
    return true;
}

Using CategoryTree in the Sidebar

Using JavaScript

Since r36920 (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 on MediaWiki: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, see Wikitext 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 your skin and customize the URL "w:Special:CategoryTree".

function AppendCategoryTreeToSidebar() {
    try {
        var node = document.getElementById( "p-tb" )
                           .getElementsByTagName('div')[0]
                           .getElementsByTagName('ul')[0];
 
        var aNode = document.createElement( 'a' );
        var liNode = 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 happened
        return;
    }
}
 
addOnloadHook( AppendCategoryTreeToSidebar );

A more generic version of this code can be found at Manual:Interface/Sidebar#content of sidebar and toolbox (javascript) .

Step by step if works easy:

$wgCategoryTreeSidebarRoot = 'Category:article_name';

Using MediaWiki: namespace pages

If you want to create a link that goes to the generic categorytree (displayed as Category tree) when you're on a non-category page, and to a particular categorytree (displayed as View as category tree, with foo being the name of the category you're viewing) when you're on a category page:

  • Add to your MediaWiki:Sidebar (right above the SEARCH is a good place) a line, ** sidebarcategorytree-url|sidebarcategorytree
  • Create a [[MediaWiki:Sidebarcategorytree]] with, say: {{#ifeq: {{NAMESPACE}}|Category|View as category tree|Category tree}}
  • Create a [[MediaWiki:Sidebarcategorytree-url]] with, say: {{#ifeq: {{NAMESPACE}}|Category|Special:CategoryTree/{{BASEPAGENAME}}|Special:CategoryTree/Categories}}

See also