Translate modifier's documentation

This commit is contained in:
bzick 2014-08-06 21:36:11 +04:00
parent 7d59b0e642
commit 0118ef192b
16 changed files with 157 additions and 94 deletions

View File

@ -1,19 +1,63 @@
Modifier date_format Модификатор date_format
==================== ====================
This formats a date and time into the given [strftime()](http://docs.php.net/strftime) format. Форматирует дату согласно указанному формату [strftime()](http://docs.php.net/ru/strftime).
Dates can be passed to Fenom as unix timestamps, DateTime objects or any string made up of month day year, parsable by [strftime()](http://docs.php.net/strftime). Даты могут быть переданы в виде временных меток unix, временных меток mysql или в виде любой строки, содержащей день,
By default format is: `%b %e, %Y`. месяц и год, которую может обработать функция [strftime()](http://docs.php.net/ru/strftime).
```smarty
{$date|date_format:$format = `%b %e, %Y`}
```
Формат по умолчанию: `%b %e, %Y`.
```smarty ```smarty
{var $ts = time()} {var $ts = time()}
{$ts|date_format:"%Y/%m/%d %H:%M:%s"} outputs 2013/02/08 21:01:43 {$ts|date_format:"%Y/%m/%d %H:%M:%s"} выведет 2013/02/08 21:01:43
{$ts|date_format:"-1 day"} outputs 2013/02/07 21:01:43 {$ts|date_format:"-1 day"} выведет вчерашний день, например 2013/02/07 21:01:43
{var $date = "2008-12-08"} {var $date = "2008-12-08"}
{$ts|date_format:"%Y/%m/%d %H:%M:%s"} outputs 2008/12/08 00:00:00 {$ts|date_format:"%Y/%m/%d %H:%M:%s"} выведет 2008/12/08 00:00:00
``` ```
[Allowed quantificators](http://docs.php.net/strftime#refsect1-function.strftime-parameters) in **date_format** [Конверсионные указатели](http://docs.php.net/ru/strftime#refsect1-function.strftime-parameters) в модификаторе **date_format**:
* %a - сокращенное название дня недели, в зависимости от текущей локали
* %A - полное название дня недели, в зависимости от текущей локали
* %b - сокращенное название месяца, в зависимости от текущей локали
* %B - полное название месяца, в зависимости от текущей локали
* %c - формат даты и времени по умолчанию для текущей локали
* %C - номер века (год, деленный на 100, представленный в виде целого в промежутке от 00 до 99)
* %d - день месяца в десятичном формате (от 01 до 31)
* %D - синоним %m/%d/%y
* %e - день месяца в десятичном формате без ведущего нуля (от 1 до 31)
* %g - Week-based year within century [00,99]
* %G - Week-based year, including the century [0000,9999]
* %h - синоним %b
* %H - часы по 24-часовым часам (от 00 до 23)
* %I - часы по 12-часовым часам (от 01 до 12)
* %j - день года (от 001 до 366)
* %k - часы по 24-часовым часам без ведущего нуля (от 0 до 23)
* %l - часы по 12-часовым часам без ведущего нуля (от 1 до 12)
* %m - номер месяца (от 01 до 12)
* %M - минуты
* %n - символ новой строки
* %p - `am' или `pm', в зависимости от заданного формата времени и текущей локали.
* %r - time in a.m. and p.m. notation
* %R - time in 24 hour notation
* %S - секунды
* %t - символ табуляции
* %T - время в формате %H:%M:%S
* %u - номер дня недели [1,7], где 1-ый день - понедельник
* %U - номер недели в году, считая первое воскресенья года первым днем первой недели
* %V - номер недели в году (по ISO 8601:1988) в диапазоне от 01 до 53, где первая неделя та, у которой хотя бы 4 дня находятся в данном году. Понедельник считается первым днем недели.
* %w - номер дня недели, где 0 - воскресенье
* %W - номер недели в году, считаю первый понедельник первым днем первой недели.
* %x - предпочтительное представление даты для текущих настроек locale без времени
* %X - предпочтительное представление времени для текущих настроек locale без даты
* %y - год в виде десятичного числа без века (от 00 до 99)
* %Y - год в виде десятичного числа включая век
* %Z - часовой пояс или имя или сокращение
* %% - буквальный символ `%'

View File

@ -1,18 +1,18 @@
Modifier ematch Модификатор ematch
============== ==============
Perform a regular expression match. Выполняет проверку на соответствие регулярному выражению.
[Read more](http://www.php.net/manual/en/reference.pcre.pattern.syntax.php) about regular expression. [Подробнее](http://www.php.net/manual/ru/reference.pcre.pattern.syntax.php) о регулярных выражениях.
``` ```
{$string|ematch:$pattern} {$string|ematch:$pattern}
``` ```
Searches `$string` for a match to the regular expression given in `$pattern`. Ищет в заданном тексте `$subject` совпадения с шаблоном `$pattern`.
```smarty ```smarty
{if $color|ematch:'/^gr[ae]y$/i'} {if $color|ematch:'/^(.*?)gr[ae]y$/i'}
some form of gray ... какой-то оттенок серого ...
{/if} {/if}
``` ```

View File

@ -1,23 +1,25 @@
Modifier ereplace Модификатор ereplace
================= =================
Perform a regular expression search and replace. Выполняет поиск и замену по регулярному выражению.
[Read more](http://www.php.net/manual/en/reference.pcre.pattern.syntax.php) about regular expression. [Подробнее](http://www.php.net/manual/ru/reference.pcre.pattern.syntax.php) о регулярных выражениях.
``` ```
{$string|replace:$pattern:$replacement} {$string|replace:$pattern:$replacement}
``` ```
Searches `$string` for matches to `$pattern` and replaces them with `$replacement`. Выполняет поиск совпадений в строке `$subject` с шаблоном pattern и заменяет их на replacement.
`$replacement` может содержать ссылки вида `\n`, `$n` или `${n}`, причем последний вариант предпочтительней.
Каждая такая ссылка будет заменена на подстроку, соответствующую n-ой подмаске. n может принимать значения от 0 до 99,
причем ссылка `\0` (либо $0) соответствует вхождению всего шаблона.
Подмаски нумеруются слева направо, начиная с единицы. Для использования обратного слэша, его необходимо продублировать.
`$replacement` may contain references of the form `\n`, `$n` or `${n}`, with the latter form being the preferred one.
Every such reference will be replaced by the text captured by the n'th parenthesized pattern. n can be from 0 to 99,
and `\0` or `$0` refers to the text matched by the whole pattern.
Opening parentheses are counted from left to right (starting from 1) to obtain the number of the capturing subpattern.
To use backslash in replacement, it must be doubled.
```smarty ```smarty
{var $string = 'April 15, 2014'} {var $string = 'April 15, 2014'}
{$string|ereplace:'/(\w+) (\d+), (\d+)/i':'${1}1, $3'} {* April1, 2014 *} {$string|ereplace:'/(\w+) (\d+), (\d+)/i':'${1}1, $3'} {* April1, 2014 *}
``` ```
**Замечание:** воизбежание скрытых ошибок при выполнении сущностей регулярные выражения стоит помещать в одинарные кавычки.

View File

@ -1,20 +1,19 @@
Modifier escape Модификатор escape
=============== ===============
The modifier escapes a string for safe insertion into the output. Используется для кодирования или экранирования спецсимволов по алгоритмам экранирования HTML, URL'ов и javascript.
It supports different escaping strategies depending on the template context. По умолчанию активирован режим экранирования HTML.
By default, it uses the HTML escaping strategy:
```smarty ```smarty
{$post.title|escape:'html'} {$text|escape:$type = 'html':$charset = 'UTF8'}
``` ```
The modifier supports the following escaping strategies: Модификатор поддерживает несколько режимов работы
* html: escapes a string for the HTML body context. * `html`: экранирует HTML сущности в строке.
* url: escapes a string for the URI or parameter contexts. * `url`: экранирует строку для использования в URL.
* js: escapes a string for the JavaScript context. * `js`: экранирует строку для использования в JavaScript.
For convenience, the `e` modifier is defined as an alias of `escape` modifier. Модификатор `e` является псевданимом модификатора от `escape`.
Second parameter is charset. Параметр `$charset` указывает кодировку для режима `html`.

View File

@ -1,19 +1,19 @@
Modifier esplit Модификатор esplit
=============== ===============
Split string by a regular expression. Разбивает строку по регулярному выражению.
[Read more](http://www.php.net/manual/en/reference.pcre.pattern.syntax.php) about regular expression. [Подробнее](http://www.php.net/manual/ru/reference.pcre.pattern.syntax.php) о регулярных выражениях.
``` ```
{$string|esplit:$pattern = '/,\s*/'} {$string|esplit:$pattern = '/,\s*/'}
``` ```
My default modifier split string by comma with spaces. По умолчанию модификатор разбивает строку по запятой с возможнымиы проблеами
```smarty ```smarty
{var $fruits1 = "banana, apple, pear"|esplit} {var $fruits1 = "banana, apple, pear"|esplit}
$fruits1 is array ["banana", "apple", "pear"] $fruits1 — массив ["banana", "apple", "pear"]
{var $fruits2 = "banana; apple; pear"|esplit:'/;\s/'} is ["banana", "apple", "pear"] {var $fruits2 = "banana; apple; pear"|esplit:'/;\s/'} is ["banana", "apple", "pear"]
$fruits2 is array ["banana", "apple", "pear"] too $fruits2 — массив ["banana", "apple", "pear"]
``` ```

View File

@ -1,7 +1,7 @@
Modifier in Модификатор in
=========== ===========
The modifier is implementation of [in](../operators.md#containment-operator) operator (performs containment test). Модификатор является реализацией оператора сдержания [in](../operators.md#Оператор-содержания).
```smarty ```smarty
{if $number|in:[1, 3, 42]} {if $number|in:[1, 3, 42]}

View File

@ -1,16 +1,16 @@
Modifier split Модификатор split
============== ==============
Join array elements with a string. Объединяет элементы массива в строку.
``` ```
{$string|join:$delimiter = ","} {$array|join:$delimiter = ","}
``` ```
Returns an array of strings, each of which is a substring of `$string` formed by splitting it on boundaries formed by the string `$delimiter`. Объединяет элементы массива с помощью строки `$delimiter`.
```smarty ```smarty
{var $fruits1 = ["banana", "apple", "pear"]} {var $fruits1 = ["banana", "apple", "pear"]}
{$fruits1|join} output banana, apple, pear {$fruits1|join} выведет banana, apple, pear
{$fruits1|join:" is not "} output banana is not apple is not pear {$fruits1|join:" is not "} выведет banana is not apple is not pear
``` ```

View File

@ -1,7 +1,7 @@
Modifier length Модификатор length
=============== ===============
The modifier returns the number of items of a sequence or mapping, or the length of a string (works with UTF8 without `mbstring`) Модификатор возвращает количество элементов массива, итератора или символов в строке (работает с UTF8).
```smarty ```smarty
{if $images|length > 5} {if $images|length > 5}

View File

@ -1,13 +1,13 @@
Modifier lower Модификатор lower
============== ==============
Modifier is used to lowercase a variable or string. Have short alias `low` Переводит строку в нижний регистр. Является эквивалентом функции PHP [strtolower()](http://docs.php.net/ru/lower).
This is equivalent to the PHP [strtolower()](http://docs.php.net/lower) function. Имеет псевданим `low`.
```smarty ```smarty
{var $name = "Bzick"} {set $name = "Bzick"}
{$name} output Bzick {$name} выведет Bzick
{$name|upper} output bzick {$name|upper} выведет bzick
{$name|up} output bzick too {$name|up} выведет bzick
``` ```

View File

@ -1,24 +1,26 @@
Modifier match Модификатор match
============== =================
Проверяет совпадение строки с паттерном.
Среднестатистический пользователь знаком с подстановками оболочки, как минимум с самыми простыми из них - `?` и `*`,
так что использование `match` вместо `ematch` для поиска в пользовательской части сайта может быть намного удобнее для пользователей,
не являющихся программистами.
Match string against a pattern.
The average user may be used to shell patterns or at least in their simplest form to `?` and `*` wildcards so using `match`
instead of `ematch` for frontend search expression input may be way more convenient for non-programming users.
``` ```
{$string|match:$pattern} {$string|match:$pattern}
``` ```
Special pattern symbols: Специальные символы:
* `?`match one or zero unknown characters. `?at` matches `Cat`, `cat`, `Bat` or `bat`, `but` not `at`. * `?`соответствие одному или нулю любых символов. `?at` соответствует `Cat`, `cat`, `Bat` или `bat`.
* `*`match any number of unknown characters. `Law*` matches `Law`, `Laws`, or `Lawyer`. * `*`соответствие любому количеству символов. `Law*` соответствует `Law`, `Laws`, или `Lawyer`.
* `[characters]`Match a character as part of a group of characters. `[CB]at` matches `Cat` or `Bat` but not `cat`, `rat` or `bat`. * `[characters]`соответствие символа группе символов. `[CB]at` соответствует `Cat` или `Bat`, но не `cat`, `rat` или `bat`.
* `\` - Escape character. `Law\*` will only match `Law*` * `\` - экрнирующийсимвол. `Law\*` будет соответвовать только `Law*`
```smarty ```smarty
{if $color|match:"*gr[ae]y"} {if $color|match:"*gr[ae]y"}
some form of gray ... какой-то оттенок серого
{/if} {/if}
``` ```

View File

@ -1,13 +1,13 @@
Modifier replace Модификатор replace
================ ================
Replace all occurrences of the search string with the replacement string Заменяет все вхождения строки поиска на строку замены
``` ```
{$string|replace:$search:$replace} {$string|replace:$search:$replace}
``` ```
This modifier returns a string with all occurrences of `$search` in subject replaced with the given `$replace` value. Этот модификатор возвращает строку, в котором все вхождения `$search` в `$subject` заменены на `$replace`.
```smarty ```smarty
{$fruits|replace:"pear":"orange"} {$fruits|replace:"pear":"orange"}

View File

@ -1,13 +1,13 @@
Modifier split Модификатор split
============== ==============
Split a string by string Разбивает строку с помощью разделителя
``` ```
{$string|split:$delimiter = ","} {$string|split:$delimiter = ","}
``` ```
Returns an array of strings, each of which is a substring of `$string` formed by splitting it on boundaries formed by the string `$delimiter`. Возвращает массив строк, полученных разбиением строки с использованием `$delimiter` в качестве разделителя.
```smarty ```smarty
{var $fruits1 = "banana,apple,pear"|split} {var $fruits1 = "banana,apple,pear"|split}

View File

@ -1,16 +1,27 @@
Modifier strip Модификатор strip
============== ==============
Заменяет все повторяющиеся пробелы, переводы строк и символы табуляции одним пробелом.
This replaces all repeated spaces and tabs with a single space, or with the supplied string. This replaces all repeated spaces and tabs with a single space, or with the supplied string.
```smarty ```smarty
{" one two "|strip} => 'one two' {" one two "|strip}
```
Результат обработки
```
one two
``` ```
Optional boolean parameter tell to the modifier strip also newline Опционально указывается флаг мультистрочности: `true` - тку же срезать переносы строк, `false` - срезать все кроме переносов строк.
```smarty ```smarty
{" multi {" multi
line line
text "|strip:true} => 'multi line text' text "|strip:true}
``` ```
Результат обработки
```
multi line text
```

View File

@ -1,16 +1,17 @@
Modifier truncate Модификатор truncate
================= =================
Modifier truncates a variable to a character length. Обрезает переменную до определенной длинны, по умолчанию - 80 символов.
В качестве необязательного второго параметра, вы можете передать строку текста, которая будет отображатся в конце обрезанной переменной. Символы этой строки не включаются в общую длинну обрезаемой строки. По умолчанию, truncate попытается обрезать строку в промежутке между словами. Если вы хотите обрезать строку строго на указаной длинне, передайте в третий необязательный параметр значение true.
```smarty ```smarty
{$long_string|truncate:$length:$etc:$by_words:$middle} {$long_string|truncate:$length:$etc:$by_words:$middle}
``` ```
* `$length`, required. Parameter determines how many characters to truncate to. * `$length`, обязателен. Определяет максимальную длинну обрезаемой строки.
* `$etc`, by default `...`. This is a text string that replaces the truncated text. * `$etc`, по умолчанию `...`. Текстовая строка, которая заменяет обрезанный текст. Её длинна НЕ включена в максимальную длинну обрезаемой строки.
* `$by_word`, by default **FALSE**. This determines whether or not to truncate at a word boundary with TRUE, or at the exact character with FALSE. * `$by_word`, по умолчанию **FALSE**. Определяет, обрезать ли строку в промежутке между словами (true) или строго на указаной длинне (false).
* `$middle`, by default **FALSE**. This determines whether the truncation happens at the end of the string with FALSE, or in the middle of the string with TRUE. * `$middle`, по умолчанию **FALSE**. Определяет, нужно ли обрезать строку в конце (false) или в середине строки (true).
```smarty ```smarty
{var $str = "very very long string"} {var $str = "very very long string"}
@ -19,4 +20,4 @@ Modifier truncates a variable to a character length.
{$str|truncate:5:" ... ":true:true} output: very ... string {$str|truncate:5:" ... ":true:true} output: very ... string
``` ```
Modifier do not use `mbstring` when works with UTF8. Модификатор работает с unicode без дополнительных расширений.

View File

@ -1,5 +1,9 @@
Modifier unescape Модификатор unescape
================= =================
`Unescape` is used to decode entity, html, js and URI. See [escape](./escape.md) Модификато `unescape` является обратным действием модификатора `escape`. Так же имеет режимы `html`, `js` and `URI`.
```smarty
{$text|unescape:$type = 'html'}
```

View File

@ -1,13 +1,13 @@
Modifier upper Модификатор upper
============== ==============
Modifier is used to uppercase a variable or string. Have short alias `up`. Переводит строку в верхний регистр. Является эквивалентом функции PHP [strtoupper()](http://docs.php.net/ru/strtoupper).
This is equivalent to the PHP [strtoupper()](http://docs.php.net/strtoupper) function. Имеет псевдоним `up`.
```smarty ```smarty
{var $name = "Bzick"} {var $name = "Bzick"}
{$name} outputs Bzick {$name} выводит Bzick
{$name|upper} outputs BZICK {$name|upper} выводит BZICK
{$name|up} outputs BZICK too {$name|up} выводит BZICK
``` ```