Справка:Сортировка

This page is a translated version of the page Help:Sorting and the translation is 6% complete.
Outdated translations are marked like this.
PD Примечание: Редактируя эту страницу, вы соглашаетесь на передачу своего вклада по лицензии CC0.
Подробнее — в проекте Помощь с общественным достоянием.
PD

Во многих ситуациях списки страниц или имён пользователей сортируются движком MediaWiki в алфавитном порядке. Кроме того, есть возможность сортировать списки данных на страницах с помощью JavaScript. This feature is supported on MediaWiki 1.9 and above, it is also installed by default on all Wikimedia projects.

A sortable table is recognized by arrows displayed beside the header within each header cell. Such a table can be sorted by one or multiple columns. When you click on an arrow, the table rows are arranged according to the chosen column. Continuously clicking the arrow alters the sorting order in the following pattern: Ascending, Descending, and then Unsorted.

You can perform secondary sorts by shift-clicking the arrows in different columns. Each shift click will set the secondary sort based on the clicked column, and this capability extends to tertiary and further sorts.

== JavaScript ==

The table sorter JavaScript code, jquery.tablesorter.js (source), is loaded via the ResourceLoader. On certain websites, the page Gadget-site.js may contain additional or modified code. JavaScript support and activation are necessary in browsers for the sorting functionality to work correctly.

== Sort modes ==

Items are sorted based on the data type of the first few rows below the header. To determine the data type, the first five non-empty rows below the header are examined upon page loading, and the most suitable format is selected. Discrepancies can occur. Additionally, specific columns can have their sorting order forced, as explained in the relevant section below.

Currently, tags like span or sup don't affect how data types are determined, but reference numbers and visible comments do.

=== Dates ===

Different date formats are accepted, even those with month names in local languages. For instance, on the German Wikipedia, "16. März 2010" is appropriately sorted as 2010-03-16.

Different numerical formats, including ones with various separators like periods, commas, apostrophes, or slashes (such as . , ' or / ), are supported. English Wikipedia typically uses the US date format, (e.g. month-day-year).

=== Numbers ===

The script can detect numbers that use either "." or "," as decimal separators, as well as numbers written in scientific notation (using "e" or "E"). By default, numbers will be sorted based on alphanumeric order by default, meaning that they will be sorted as strings rather than numerical values. This may result in unexpected sortings, such as "9" coming after "10". However, this default behavior can be overridden if desired.

=== Text ===



При алфавитной сортировке списков движком MediaWiki символы упорядочиваются с помощью w:Collation#Alphabetical. Эта функция корректно упорядочивает символы с диакритикой в соответствии с PageContentLanguage.

Webview для Android не поддерживают эту функцию, поэтому необходима обратная совместимость со старыми механизмами сортировки. Порядок совпадает с порядком кодов символов в Юникоде. Некоторые наиболее распространённые символы следуют в указанном ниже порядке (по возрастанию):

 
! " # $ % & ' ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ? @ A B C
D E F G H I J K L M N O P Q R S T U V W X Y Z [ \ ] ^ _ ` a b c d e f g
h i j k l m n o p q r s t u v w x y z { | } ~
 
¡ ¢ £ ¤ ¥ ¦ § ¨ © ª « ¬
­
® ¯ ° ± ² ³ ´ µ · ¸ ¹ º » ¼ ½ ¾ ¿ À Á Â Ã Ä Å Æ Ç È É Ê Ë Ì Í Î Ï Ð
Ñ Ò Ó Ô Õ Ö × Ø Ù Ú Û Ü Ý Þ ß à á â ã ä å æ ç è é ê ë ì í î ï ð ñ ò ó ô
õ ö ÷ ø ù ú û ü ý þ ÿ Ā ā Ă ă Ą ą Ć ć Ĉ ĉ Ċ ċ Č č Ď ď Đ đ Ē ē Ĕ ĕ Ė ė Ę
ę Ě ě Ĝ ĝ Ğ ğ Ġ ġ Ģ ģ Ĥ ĥ Ħ ħ Ĩ ĩ Ī ī Ĭ ĭ Į į İ ı IJ ij Ĵ ĵ Ķ ķ ĸ Ĺ ĺ Ļ ļ
Ľ ľ Ŀ ŀ Ł ł Ń ń Ņ ņ Ň ň ʼn Ŋ ŋ Ō ō Ŏ ŏ Ő ő Œ œ Ŕ ŕ Ŗ ŗ Ř ř Ś ś Ŝ ŝ Ş ş Š
š Ţ ţ Ť ť Ŧ ŧ Ũ ũ Ū ū Ŭ ŭ Ů ů Ű ű Ų ų Ŵ ŵ Ŷ ŷ Ÿ Ź ź Ż ż Ž ž ſ Ə ƒ Ǻ ǻ Ǽ
ǽ Ǿ ǿ Ș ș Ț ț ə ˆ ˇ ˉ ˘ ˙ ˚ ˛ ˜ ˝ ΄ ΅ Ά · Έ Ή Ί Ό Ύ Ώ ΐ Α Β Γ Δ Ε Ζ Η Θ
Ι Κ Λ Μ Ν Ξ Ο Π Ρ Σ Τ Υ Φ Χ Ψ Ω Ϊ Ϋ ά έ ή ί ΰ α β γ δ ε ζ η θ ι κ λ μ ν
ξ ο π ρ ς σ τ υ φ χ ψ ω ϊ ϋ ό ύ ώ Ѐ Ё Ђ Ѓ Є Ѕ І Ї Ј Љ Њ Ћ Ќ Ѝ Ў Џ А Б В
Г Д Е Ж З И Й К Л М Н О П Р С Т У Ф Х Ц Ч Ш Щ Ъ Ы Ь Э Ю Я а б в г д е ж
з и й к л м н о п р с т у ф х ц ч ш щ ъ ы ь э ю я ѐ ё ђ ѓ є ѕ і ї ј љ њ
ћ ќ ѝ ў џ Ґ ґ
Ω

Категории

Категории сортируются иначе, чем другие списки. Итоговый порядок зависит от конфигурации вики и задаётся через Руководство:$wgCategoryCollation . The default since MediaWiki 1.17 is the Unicode code point order as above, but with all the lowercase letters turned into uppercase letters. More complex orderings are possible.

=== Forcing the sort mode of a column ===

Adding data-sort-type="..." to the header lets you control how a table is sorted. This feature is derived from tablesorter.com (webarchive). Valid values for "data-sort-type" include the following which are not case-sensitive: Certainly! Here's a randomized list based on your provided values:

  • Currency
  • number
  • isoDate
  • time
  • IPAddress
  • usLongDate
  • date
  • text
  • url

For example: Wikitext

{|class="wikitable sortable"
!data-sort-type="date"|Date!!Name!!Height!!data-sort-type="number"|Salary
|-
|01.10.1977||Smith||1.85||1,000.000
|-
|11.6.1972||Ray||1.89||900.000
|-
|1.9.1992||Bianchi||1.72||2,000.50
|}

Rendering

Date Name Height Salary
01.10.1977 Smith 1.85 1,000.000
11.6.1972 Ray 1.89 900.000
1.9.1992 Bianchi 1.72 2,000.50

=== Specifying a sort key ===

You can adjust how cells are sorted or parsed if needed. For instance, if a cell says "John Smith" but should be sorted under "Smith", you can use the data-sort-value="..." attribute to achieve this.

Wikitext

{|class="wikitable sortable"
!Name and Surname!!Height
|-
|data-sort-value="Smith, John"|John Smith||1.85
|-
|data-sort-value="Ray, Ian"|Ian Ray||1.89
|-
|data-sort-value="Bianchi, Zachary"|Zachary Bianchi||1.72
|}

Rendering

Name and Surname Height
John Smith 1.85
Ian Ray 1.89
Zachary Bianchi 1.72

== Controlling sorting and display ==

To ensure certain text isn't sorted but still displayed, use data-sort-type="...". You can then append additional text after values, like "200 approx" or "100<sup style="color:blue" title="link to Reference">[1]". An empty cell sorts as "-Infinity". If a cell contains a range of dates or numbers (for example, from 2 to 5), use data-sort-value="...".

=== Examples ===

The first column sorts plain numbers. The second column sorts more content as numbers using data-sort-type="number" in the table header. The fourth column defines numeric sort values independently of cell content using data-sort-value="...".

numbers data-sort-type="number" data-sort-type="number"
-8e3 -8 e3 -8 e3
-3e-3 -3 e-3 -3 e-3
2.000 2-5 km² data-sort-value="3.5" 2-5 km²
3.99 3.99 km² 3.99 km²
4 4 km² 4 km²
90 % 90 Percent data-sort-value="90" about 90 Percent
1E2 100[1] 100[1]
1,000,000.0 1 000 000.0 data-sort-value="1e6" one Million

The way commas (,) and decimal points (.) are displayed in Mediawiki depends on the language settings. Currency symbols and the percentage (%) symbol are sorted numerically based on these settings.

currencies
$ 9
$ 80
$ 70
$ 600
currencies
9 €
80 €
70 €
600 €
currencies
£ 9
£ 80
£ 70
£ 600
currencies
¥ 9
¥ 80
¥ 70
¥ 600
percent
9 %
80 %
70 %
600 %
numbers
−7e270
-1.4285714285714E-13
999e9
7e270

== Secondary sort key ==

You can sort data by columns, with Column A as the primary sort key. If Column A has equal values, use Column B as the secondary key. Click Column A's sort button once or twice, then while holding shift, click Column B's sort button once or twice for further refinement.

For example:

Click on the "Text" column first, then hold down the shift key and click on the "Numbers" column. You'll notice that the items are sorted based on text first and then numbers.

Numbers Text Dates Currency More text
4 a 01.Jan.2005 4.20 row 1
5 a 05/12/2006 7.15 row 2
1 b 02-02-2004 5.00 row 3
1 a 02-02-2004 5.00 row 4
2 x 13-apr-2005 row 5
2 a 13-apr-2005 row 6
3 a 17.aug.2006 6.50 row 7
3 z 25.aug.2006 2.30 row 8
3 z 28.aug.2006 5.50 row 9
3 z 31.aug.2006 3.77 row 10
3 z 01.sep.2006 1.50 row 11
Bottom

== Additional features ==

=== Excluding the last row from sorting ===

You can skip sorting the last row of a table by marking it with class="sortbottom". You can also exclude it from sorting by declaring it as a footer with an exclamation mark (!).

Wikitext

{|class="wikitable sortable"
!Name!!Surname!!Height
|-
|John||Smith||1.85
|-
|Ron||Ray||1.89
|-
|Mario||Bianchi||1.72
|- class="sortbottom"
! !!Average:||1.82
|}

Rendering

Name Surname Height
John Smith 1.85
Ron Ray 1.89
Mario Bianchi 1.72
Average: 1.82

=== Excluding the first row from sorting ===

You can exclude the first row by using the class="sorttop".

Wikitext

{|class="wikitable sortable"
!Name!!Surname!!Height
|- class="sorttop"
! !!Average:||1.82
|-
|John||Smith||1.85
|-
|Ron||Ray||1.89
|-
|Mario||Bianchi||1.72
|}

Rendering

Name Surname Height
Average: 1.82
John Smith 1.85
Ron Ray 1.89
Mario Bianchi 1.72

=== Making a column unsortable ===

To stop a column from being sortable, use class="unsortable" in its header cell's attributes.

Wikitext

{|class="wikitable sortable"
!Numbers!!Alphabet!!Dates!!Currency!!class="unsortable"|Unsortable
|-
|1||Z||02-02-2004||5.00||This
|-
|2||y||13-apr-2005||||Column
|-
|3||X||17.aug.2006||6.50||Is
|-
|4||w||01.Jan.2005||4.20||Unsortable
|-
|5||V||05/12/2006||7.15||See?
|-
!Total: 15!!!!!!Total: 29.55!!
|-
|}

Rendering

Numbers Alphabet Dates Currency Unsortable
1 Z 02-02-2004 5.00 This
2 y 13-apr-2005 Column
3 X 17.aug.2006 6.50 Is
4 w 01.Jan.2005 4.20 Unsortable
5 V 05/12/2006 7.15 See?
Total: 15 Total: 29.55 Original example

=== Keeping some rows together ===

To allow an uncolumned row to always stay beneath the columned row above it, no matter how you sort them, use class="expand-child" in the row's attribute.

Wikitext

{| class="wikitable sortable"
! style="width:9em"| Country !!data-sort-type="number"| Area
|-
| France
| 674 843 km²
|- class="expand-child" style="font-size:85%; line-height:1.2; color:gray"
| colspan="2" | In Paris is the Eiffel Tower.
|-
| U.K.
| 242 495 km²
|- class="expand-child" style="font-size:85%; line-height:1.2; color:gray"
| colspan="2" | In the U.K. you cannot pay with euros.
|- class="expand-child" style="font-size:85%; line-height:1.2; color:gray"
| colspan="2" | And you drive on the left side of the road.
|-
| Germany
| 357 168 km²
|- class="expand-child" style="font-size:85%; line-height:1.2; color:gray"
| colspan="2" | Germany includes the former DDR.
|}

Rendering

Country Area
France 674 843 km²
In Paris is the Eiffel Tower.
U.K. 242 495 km²
In the U.K. you cannot pay with euros.
And you drive on the left side of the road.
Germany 357 168 km²
Germany includes the former DDR.

If you put in data-sort-value the same content as above row, keep this rows also together. The original mutual order of these rows is preserved. A better way for this is class expand-child, see above #Keeping some rows together.

Example where data-sort-value is used is the case for the rows about the Netherlands:

{|class="wikitable sortable"
!Country/province!!Capital
|-
|France||Paris
|-
|Netherlands||Amsterdam
|-
|data-sort-value=Netherlands|South Holland||data-sort-value=Amsterdam|The Hague
|-
|U.K.||London
|}
Country/province Capital
France Paris
Netherlands Amsterdam
South Holland The Hague
U.K. London

== Special dates ==

To represent years Before Christ (BC) subtract the BC year from 10,000. For instance, -62 BC would be 10,000 - 62 = 9938.

For example, September 23, 62 BC would be represented as 9938-09-23.

If a table column has incomplete dates, sorting won't be an issue. If only a year and month are provided, it's sorted before the first day of that month. Similarly, if only a year is given, it's sorted before the first month or day of that year.

Wikitext

{| class="wikitable sortable"
|-
! Date
|-
| 2022-01-01
|-
| 2023-12-31
|-
| 2024
|-
| 2024-04
|-
| 2024-04-00
|-
| 2024-05
|-
| 2024-05-00
|}

Rendering

Date
2022-01-01
2023-12-31
2024
2024-04
2024-04-00
2024-05
2024-05-00

=== Using #time ===

You can use the parser function #time and HTML tags to display a specific date range. By adding the HTML tag &301715438417 before the displayed date, you can manipulate the way the date is shown. This method works for dates between January 1, 111 CE, and December 31, 9999 CE, using the proleptic Gregorian calendar. The added value ensures all values are positive and uniform in length. Placing "&" before the expression forces string sorting mode.

You can input dates and times using any PHP format for date and time. Remember, if you're specifying just a year, you must include a month (usually January) in the background.

For example using date:

input date text date and time as interpreted, with hidden sort key input with visible sort key input with hidden sort key Unix time
010203 &301715389323 11 май 2024 01:02:03 &301715389323 010203 &301715389323 010203 1715389323
1/2 &301704153600 02 янв 2024 00:00:00 &301704153600 1/2 &301704153600 1/2 1704153600
1/2/3 &301041465600 02 янв 2003 00:00:00 &301041465600 1/2/3 &301041465600 1/2/3 1041465600
1-2-2003 &301044057600 01 фев 2003 00:00:00 &301044057600 1-2-2003 &301044057600 1-2-2003 1044057600
1-2-3 &300981158400 03 фев 2001 00:00:00 &300981158400 1-2-3 &300981158400 1-2-3 981158400
2007 &301167609600 01 янв 2007 00:00:00 &301167609600 2007 &301167609600 2007 1167609600
1 Jan 111, 00:00:00 &241335609600 01 янв 0111 00:00:00 &241335609600 1 Jan 111, 00:00:00 &241335609600 1 Jan 111, 00:00:00 -58664390400
31 Dec 9999, 23:59:59 &553402300799 31 дек 9999 23:59:59 &553402300799 31 Dec 9999, 23:59:59 &553402300799 31 Dec 9999, 23:59:59 253402300799
Sep 1970 &300020995200 01 сен 1970 00:00:00 &300020995200 Sep 1970 &300020995200 Sep 1970 20995200
1970 &300000000000 01 янв 1970 00:00:00 &300000000000 1970 &300000000000 1970 0
Jun 2007 or later &301180656000 01 июн 2007 00:00:00 or later &301180656000 Jun 2007 or later &301180656000 Jun 2007 or later 1180656000 or later
Jun 2007 perhaps earlier &301180656000 01 июн 2007 00:00:00 perhaps earlier &301180656000 Jun 2007 perhaps earlier &301180656000 Jun 2007 perhaps earlier 1180656000 perhaps earlier
2007-6 &301180656000 01 июн 2007 00:00:00 &301180656000 2007-6 &301180656000 2007-6 1180656000
Jun 2007 &301180656000 01 июн 2007 00:00:00 &301180656000 Jun 2007 &301180656000 Jun 2007 1180656000
4 Jun 2007 &301180915200 04 июн 2007 00:00:00 &301180915200 4 Jun 2007 &301180915200 4 Jun 2007 1180915200
3 Jul 2007 &301183420800 03 июл 2007 00:00:00 &301183420800 3 Jul 2007 &301183420800 3 Jul 2007 1183420800
12 Aug 2006 &301155340800 12 авг 2006 00:00:00 &301155340800 12 Aug 2006 &301155340800 12 Aug 2006 1155340800
1 Mar 2006 -1day &301141084800 28 фев 2006 00:00:00 &301141084800 1 Mar 2006 -1day &301141084800 1 Mar 2006 -1day 1141084800
1 Mar 2008 -1day &301204243200 29 фев 2008 00:00:00 &301204243200 1 Mar 2008 -1day &301204243200 1 Mar 2008 -1day 1204243200
1 Mar 2010 -1day &301267315200 28 фев 2010 00:00:00 &301267315200 1 Mar 2010 -1day &301267315200 1 Mar 2010 -1day 1267315200
1 Mar 1900 -1day &297796022400 28 фев 1900 00:00:00 &297796022400 1 Mar 1900 -1day &297796022400 1 Mar 1900 -1day -2203977600
1 Mar 1600 -1day &288329001600 29 фев 1600 00:00:00 &288329001600 1 Mar 1600 -1day &288329001600 1 Mar 1600 -1day -11670998400
Jun 1607 &288557875200 01 июн 1607 00:00:00 &288557875200 Jun 1607 &288557875200 Jun 1607 -11442124800
20240511144017 &301715438417 11 май 2024 14:40:17 &301715438417 20240511144017 &301715438417 20240511144017 1715438417
yesterday &301715299200 10 май 2024 00:00:00 &301715299200 yesterday &301715299200 yesterday 1715299200
today &301715385600 11 май 2024 00:00:00 &301715385600 today &301715385600 today 1715385600
tomorrow &301715472000 12 май 2024 00:00:00 &301715472000 tomorrow &301715472000 tomorrow 1715472000
1week &301716043217 18 май 2024 14:40:17 &301716043217 1week &301716043217 1week 1716043217
-1week &301714833617 04 май 2024 14:40:17 &301714833617 -1week &301714833617 -1week 1714833617
1day &301715524817 12 май 2024 14:40:17 &301715524817 1day &301715524817 1day 1715524817
-1day &301715352017 10 май 2024 14:40:17 &301715352017 -1day &301715352017 -1day 1715352017
1month &301718116817 11 июн 2024 14:40:17 &301718116817 1month &301718116817 1month 1718116817
-1month &301712846417 11 апр 2024 14:40:17 &301712846417 -1month &301712846417 -1month 1712846417
1year &301746974417 11 май 2025 14:40:17 &301746974417 1year &301746974417 1year 1746974417
-1year &301683816017 11 май 2023 14:40:17 &301683816017 -1year &301683816017 -1year 1683816017
1000year &333272347217 11 май 3024 14:40:17 &333272347217 1000year &333272347217 1000year 33272347217
10000month &328013006417 11 сен 2857 14:40:17 &328013006417 10000month &328013006417 10000month 28013006417
1000000day &388115438417 08 апр 4762 14:40:17 &388115438417 1000000day &388115438417 1000000day 88115438417
10000000hour &337715438417 26 фев 3165 06:40:17 &337715438417 10000000hour &337715438417 10000000hour 37715438417
1000000000minute &361715438417 08 сен 3925 01:20:17 &361715438417 1000000000minute &361715438417 1000000000minute 61715438417
100000000000second &401715438417 27 мар 5193 00:26:57 &401715438417 100000000000second &401715438417 100000000000second 101715438417
7980year &Expression error: Unexpected < operator. Error: #time only supports years up to 9999. &Expression error: Unexpected < operator. 7980year &Expression error: Unexpected < operator. 7980year Error: #time only supports years up to 9999.
-1890year &242072740817 11 май 0134 14:40:17 &242072740817 -1890year &242072740817 -1890year -57927259183
Mon &301715558400 13 май 2024 00:00:00 &301715558400 Mon &301715558400 Mon 1715558400
Tue &301715644800 14 май 2024 00:00:00 &301715644800 Tue &301715644800 Tue 1715644800
Wed &301715731200 15 май 2024 00:00:00 &301715731200 Wed &301715731200 Wed 1715731200
Thu &301715817600 16 май 2024 00:00:00 &301715817600 Thu &301715817600 Thu 1715817600
Fri &301715904000 17 май 2024 00:00:00 &301715904000 Fri &301715904000 Fri 1715904000
Sat &301715385600 11 май 2024 00:00:00 &301715385600 Sat &301715385600 Sat 1715385600
Sun &301715472000 12 май 2024 00:00:00 &301715472000 Sun &301715472000 Sun 1715472000
&Expression error: Unexpected < operator. Error: Invalid time. &Expression error: Unexpected < operator. &Expression error: Unexpected < operator. Error: Invalid time.
unknown &Expression error: Unexpected < operator. Error: Invalid time. &Expression error: Unexpected < operator. unknown &Expression error: Unexpected < operator. unknown Error: Invalid time.

To use dates before 111 AD, add a multiple of 400 (like 6000) to all years. This shifts the range to start from January 1st, -5889, aat 00:00:00, and ends on December 31st, 3999, at 23:59:59, without altering the calendar system.

See also:

== Cell spanning multiple rows/cells ==

A cell that extends across multiple rows or columns is considered equivalent to having multiple cells with identical values.

rowspan
Date Name Height
01.10.1977 Smith 1.85
11.06.1972 Adams
01.09.1992 Bianchi 1.72
colspan
A B C
A 2 1
B 1 3
C 2

Since MediaWiki Version 1.26 wmf23 (Sept. 2015), sorting colspanned cells works properly. Also, any missing cells at the end of a row will turn into empty cells after the first sort.

=== Colspanned cells ===

Sort modes are detected separately for each column containing colspanned cells. You can set a sort mode for all colspanned columns by including data-sort-type in the header.

To implement separate sort keys for each column within a colspanned cell, utilize a CSS trick described here: Ensure an equal number of cells in each row for sortable columns. If there's a mismatch, all columns become sortable. This rule should apply up to and including the last sortable column. However, employing a CSS workaround allows for a difference between the displayed number of cells in a row and the formal count. For instance, two formal cells can appear as one by adjusting the width of the first column, shifting the content of the second cell to the left, increasing its width by the same measure, and concealing the cell border that would typically be visible. Concealed sort keys enable managing the sorting order of specific rows in relation to each column.

For example:

Country Capital
France Paris
Z M
Sorting with respect to the first column this row sorts like Z, with respect to the second column like M
U.K. London

== Static column ==

To make a static column, like one with row numbers, use two tables placed next to each other. Make sure each row in both tables has the same height.

Number
1
2
Country Capital
The Netherlands Amsterdam (although The Hague is the seat of government)
France Paris

The formatting can be modified to present everything in a unified table. If a row is too short for the text in a cell, the browser will expand it, disrupting the alignment.

== Default order ==

You can't show a table sorted by a column without the user clicking on it. By default, table rows appear in the order as the wikitext. To display a table sorted by a specific column, you'll need to arrange the wikitext accordingly.

=== Sorting the wikitext of a table ===

To create a new default sorting order semi-automatically do the following:

  1. Rearrange the table's wikitext without the top and bottom lines.
  2. Replace the cell separators with a unique code that doesn't contain a "|" by using "find and replace".
  3. Replace any pipes within table cells with a code, and then substitute that code with a newline character preceded by it (indicating the start of a new row).
  4. Use the Sort module (referenced in Module talk:Sort) on Special:ExpandTemplates. To sort the items between the pipes and produce the desired separator, expand templates and add {{#invoke:Sort|f||- | (with the newline) before and }} after the wikitext.
  5. Delete the items that begin with "-" and a newline.
  6. Change the temporary codes for the cell separators and pipes inside the cells to restore them.

This sorting method relies on the wikitext in each row, primarily sorting by the content of the first column. The second column serves as a secondary key. However, wikitext codes in the first column cells before the content can impact the order.

=== Using JavaScript to trigger client-side table sorting ===

To "re-sort" a table automatically on the client side as the page loads, add Gadget-site.js (as if the user had clicked the header.) This code snippet below uses the first column to sort every table on a set of pages in ascending order (see Tablesorter documentation).

function isSortedTablePage() {
    return ( wgPageName == "Page_To_Sort"  || wgPageName == "Other_Page_To_Sort" );
}

jQuery( document ).ready( function( $ ) {
    // wrapped in "mw.loader.using" so this doesn't execute until Tablesorter has loaded
    mw.loader.using( 'jquery.tablesorter', function() {
        if( isSortedTablePage() ) $('table.sortable').tablesorter( {sortList: [ { 0: 'asc'} ]} )
        // or look for tables with an ID attribute of "sortMe" on any page
        // $( '#sortMe' ).tablesorter( {sortList: [ { 0: 'asc'} ]} )
    } );
} );

Заметка Заметка: Clicking on headers causes this to disrupt sorting. While it initially sorts in ascending order based on the clicked header, it fails to reverse the sorting direction when clicked again.

== Basic alphabetic sorting order ==

demo
!
"
#
$
%
&
'
(
)
*
+
,
-
.
/
0
9
:
;
<
=
>
?
@
[
\
]
^
_
`
A
Z
a
z
A1
Z1
a1
z1
{
|
}
~
É
é
É1
é1

Uppercase and lowercase letters are treated as equivalent when sorting alphabetically. So, two-character entries such as "A1" and "a1" are considered to occupy the same position in sorting. This sorting method converts uppercase letters to lowercase using a simple 1-to-1 conversion table (Limited to the Basic Multilingual Plane of Unicode, its coverage depends on browser versions and their current implementation of the Unicode Character Database.). However, it also considers characters with diacritics and other symbols, digits, or special whitespaces. These characters are sorted based on their binary encoding after case folding, utilizing the UTF-16 code unit order as exposed and interpreted through parsed HTML DOM in JavaScript, rather than the UTF-8 code unit order in the HTML page or the code points as one might expect for characters encoded in supplementary planes. Furthermore, Unicode text is not being normalized, meaning strings that are canonically equivalent may not compare as expected due to minor binary differences. To ensure consistency, it's advisable to encode MediaWiki pages using Normalized Form C (preComposed), as suggested by HTML standards. As of today, client-side Javascript code still lacks implementation for UCA-based sorting. However, certain wikis are introducing a simplified version of multilevel collation by employing customized replacement rules tailored for specific languages.

== Server issue ==

MediaWiki code on the server automatically replaces a standard space before "!" with a non-breaking space  , impacting sorting order. To prevent this, use for the blank space, or enclose the exclamation mark within </code> and <code> tags. This follows French typographic rules where spaces should come before exclamation marks and stay unbreakable when needed. It's a helpful editing feature for common text scenarios.

== Persistent sort states using cookies ==

Including the below code snippet in your Gadget-site.js file will enable sortable tables to retain their column sorting states via cookies. This ensures that the tables will appear the same the next time the page is visited. Each sortable table should have a distinct id attribute for its state to be saved in the cookie.

addOnloadHook( function() {
    jQuery('.sortable').each( function() {
        var id = jQuery(this).attr('id');
        document.shCookie = getCookie('sortheader-'+id);
        document.sortheaderId = 0;
        jQuery('#'+id+' a.sortheader').each( function() {
            var id = jQuery(this).parent().parent().parent().parent().attr('id');
            var sh = document.sortheaderId++;
            if( sh+100 == document.shCookie ) { ts_resortTable(this); ts_resortTable(this); }
            if( sh == document.shCookie ) { ts_resortTable(this); sh += 100; }
            jQuery(this).bind('click', {id: id, sh: sh}, function(e) {
                setCookie('sortheader-'+e.data.id, e.data.sh, 1);
                e.data.sh += e.data.sh < 100 ? 100 : -100;
            });
        });
    });
});

function setCookie(c_name,value,exdays) {
    var exdate=new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
    document.cookie=c_name + "=" + c_value;
}

function getCookie(c_name) {
    var i,x,y,ARRcookies=document.cookie.split(";");
    for (i=0;i<ARRcookies.length;i++) {
        x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
        y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
        x=x.replace(/^\s+|\s+$/g,"");
        if (x==c_name) return unescape(y);
    }
}

См. также

Other examples: