From e88d416df19f6e8a109ae918e2dc2a00e633c2e9 Mon Sep 17 00:00:00 2001 From: bzick Date: Fri, 2 Jan 2015 22:44:23 +0300 Subject: [PATCH] Docs: add english docs --- docs/en/readme.md | 14 +- docs/en/syntax.md | 328 ++++++++++++++++++++++++++++++++++--------- docs/ru/operators.md | 6 +- docs/ru/readme.md | 2 +- docs/ru/syntax.md | 18 +-- 5 files changed, 284 insertions(+), 84 deletions(-) diff --git a/docs/en/readme.md b/docs/en/readme.md index 9e3d358..00e0920 100644 --- a/docs/en/readme.md +++ b/docs/en/readme.md @@ -1,8 +1,6 @@ Documentation ============= -**Please, help translate documentation to english or fix typos. [Read more](./helpme.md).** - ### Fenom * [Quick start](./start.md) @@ -11,7 +9,13 @@ Documentation * [For developers](./dev/readme.md) * [Configuration](./configuration.md) * [Syntax](./syntax.md) -* [Operators](./operators.md) + * [Variables](./syntax.md#Variables) + * [Values](./syntax.md#Values) + * [Arrays](./syntax.md#Arrays) + * [Operators](./operators.md) + * [Modificators](./syntax.md#Modificators) + * [Tags](./syntax.md#Tags) + * [Tag configuration](./syntax.md#Tag-configuration) *** @@ -19,7 +23,7 @@ Documentation [Usage](./syntax.md#tags) -* [var](./tags/var.md) — define variable +* [set](./tags/var.md), `add` and `var` — define variables * [if](./tags/if.md), `elseif` and `else` — conditional statement * [foreach](./tags/foreach.md), `foreaelse`, `break` and `continue` — traversing items in an array or object * [for](./tags/for.md), `forelse`, `break` and `continue` — loop statement @@ -72,7 +76,7 @@ Documentation * [Comparison operators](./operators.md#comparison-operators) — `>`, `>=`, `<`, `<=`, `==`, `!=`, `!==`, `<>` * [Bitwise operators](./operators.md#bitwise-operators) — `|`, `&`, `^`, `~$var`, `>>`, `<<` * [Assignment operators](./operators.md#assignment-operators) — `=`, `+=`, `-=`, `*=`, `/=`, `%=`, `&=`, `|=`, `^=`, `>>=`, `<<=` -* [String concatenation operator](./operators.md#string-operator) — `$str1 ~ $str2` +* [String concatenation operators](./operators.md#string-operators) — `$str1 ~ $str2`, `$str1 ~~ $str2`, `$str1 ~= $str2` * [Ternary operators](./operators.md#ternary-operators) — `$a ? $b : $c`, `$a ! $b : $c`, `$a ?: $c`, `$a !: $c` * [Check operators](./operators.md#check-operators) — `$var?`, `$var!` * [Test operator](./operators.md#test-operator) — `is`, `is not` diff --git a/docs/en/syntax.md b/docs/en/syntax.md index 7c1edb4..aa5803a 100644 --- a/docs/en/syntax.md +++ b/docs/en/syntax.md @@ -76,16 +76,16 @@ Below is complex example: ### System variable -Unnamed system variable starts with `$.` and allows access to global variables and template information: +Unnamed system variable starts with `$.` and allows access to global system variables and template information: -* `$.get` is `$_GET`. -* `$.post` is `$_POST`. -* `$.cookie` is `$_COOKIE`. -* `$.session` is `$_SESSION`. -* `$.globals` is `$GLOBALS`. -* `$.request` is `$_REQUEST`. -* `$.files` is `$_FILES`. -* `$.server` is `$_SERVER`. +* `$.get` — array `$_GET`. +* `$.post` — array `$_POST`. +* `$.cookie` — array `$_COOKIE`. +* `$.session` — array `$_SESSION`. +* `$.globals` — array `$GLOBALS`. +* `$.request` — array `$_REQUEST`. +* `$.files` — array `$_FILES`. +* `$.server` — array `$_SERVER`. * `$.env` is `$_ENV`. * `$.tpl.name` returns current template name. * `$.tpl.schema` returns current schema of the template. @@ -98,6 +98,165 @@ Unnamed system variable starts with `$.` and allows access to global variables a {/if} ``` + +Безименная системная переменная начинается с `$.` и предоставляет доступ к глобальным системным переменным и системной информации: + +* `$.env` — array `$_ENV`. +* `$.get` — array `$_GET`. +* `$.post` — array `$_POST`. +* `$.files` — array `$_FILES`. +* `$.cookie` — array `$_COOKIE`. +* `$.server` — array `$_SERVER`. +* `$.session` — array `$_SESSION`. +* `$.globals` — array `$GLOBALS`. +* `$.request` — array `$_REQUEST`. +* `$.tpl.name` returns name for current template. +* `$.tpl.basename` returns name without schema for current template. +* `$.tpl.scm` returns schema for current template. +* `$.tpl.options` returns options as integer for current template. +* `$.tpl.depends` +* `$.tpl.time` returns last modified timestamp for current template +* `$.version` returns Fenom version. +* `$.const` returns the value of a PHP constant: `$.const.PHP_EOL` get value of constant `PHP_EOL`. + Supported namespace for constants, use dot instead of back-slash for namespace separators: `$.const.Storage.FS::DIR_SEPARATOR` get value of constant `Storage\FS::DIR_SEPARATOR`. + But if constant `Storage\FS::DIR_SEPARATOR` does not exists then constant `Storage\FS\DIR_SEPARATOR` will be taken. +* `$.php`call PHP static method. `$.php.Storage.FS::put($filename, $data)` calls method `Storage\FS::put($filename, $data)`. + `$.php.Storage.FS.put($filename, $data)` `Storage\FS\put($filename, $data)` +* System function `$.fetch($name, $values)` calls Fenom::fetch() in template. `$name` — template name, + `$values` — additional variables. +* also you may [add](./ext/extend.md#Extends-system-variable) yours system variables and functions. + + +## Scalar values + +### Strings + +A string literal can be specified in two different ways: double quotes (`"string"`) and single quotes (`'string'`). + +#### Double quotes + +If the string is enclosed in double-quotes `"`, Fenom will interpret more escape sequences for special characters: + + +| Последовательность | Значение | +|---------------------|----------| +| `\n` | linefeed (LF or 0x0A (10) in ASCII) +| `\r` | carriage return (CR or 0x0D (13) in ASCII) +| `\t` | horizontal tab (HT or 0x09 (9) in ASCII) +| `\v` | vertical tab (VT or 0x0B (11) in ASCII) +| `\f` | form feed (FF or 0x0C (12) in ASCII) +| `\\` | backslash +| `\$` | dollar sign +| `\"` | double-quote +| `\[0-7]{1,3}` | the sequence of characters matching the regular expression is a character in octal notation +| `\x[0-9A-Fa-f]{1,2}`| the sequence of characters matching the regular expression is a character in hexadecimal notation + +The most important feature of double-quoted strings is the fact that variable names will be expanded. +There are two types of syntax: a simple one and a complex one. The simple syntax is the most common and convenient. +It provides a way to embed a variable, an array value, or an object property in a string with a minimum of effort. +The complex syntax can be recognised by the curly braces surrounding the expression. + +##### Simple syntax + +If a dollar sign `$` is encountered, the parser will greedily take as many tokens as possible to form a valid variable name. +Enclose the variable name in curly braces to explicitly specify the end of the name. + +```smarty +{"Hi, $username!"} outputs "Hi, Username!" +``` + +For anything more complex, you should use the complex syntax. + +##### Complex syntax + +This isn't called complex because the syntax is complex, but because it allows for the use of complex expressions. +Any scalar variable, array element or object property with a string representation can be included via this syntax. +Simply write the expression the same way as it would appear outside the string, and then wrap it in `{` and `}`. +Since `{` can not be escaped, this syntax will only be recognised when the `$` immediately follows the `{`. +Use `{\$` to get a literal `{$`. Some examples to make it clear: + + +```smarty +{"Hi, {$user.name}!"} outputs: Hi, Username! +{"Hi, {$user->name}!"} outputs: Hi, Username! +{"Hi, {$user->getName()}!"} outputs: Hi, Username! +{"Hi, {\$user->name}!"} outputs: Hi, {\$user->name}! +``` + +Allows modifiers and operators: + +```smarty +{"Hi, {$user.name|up}!"} outputs: Hi, USERNAME! +{"Hi, {$user.name|up ~ " (admin)"}!"} outputs: Hi, USERNAME (admin)! +``` + +#### Single quotes + +The simplest way to specify a string is to enclose it in single quotes (the character `'`). +To specify a literal single quote, escape it with a backslash (`\`). +To specify a literal backslash, double it (`\\`). +All other instances of backslash will be treated as a literal backslash: this means that the other escape sequences you might be used to, such as `\r` or `\n`, will be output literally as specified rather than having any special meaning. + +```smarty +{'Hi, $foo'} outputs: 'Hi, $foo' +{'Hi, {$foo}'} outputs: 'Hi, {$foo}' +{'Hi, {$user.name}'} outputs: 'Hi, {$user.name}' +{'Hi, {$user.name|up}'} outputs: "Hi, {$user.name|up}" +``` + +### Integers + +Integers can be specified in decimal (base 10), hexadecimal (base 16), octal (base 8) or binary (base 2) notation, optionally preceded by a sign (- or +). + +To use octal notation, precede the number with a 0 (zero). +To use hexadecimal notation precede the number with 0x. +To use binary notation precede the number with 0b. + +``smarty +{var $a = 1234} decimal number +{var $a = -123} a negative number +{var $a = 0123} octal number (equivalent to 83 decimal) +{var $a = 0x1A} hexadecimal number (equivalent to 26 decimal) +{var $a = 0b11111111} binary number (equivalent to 255 decimal) +``` + +**Notice** +Binary notation (`0b1011011`) unavailable on PHP older than 5.3. + +**Notice** +The size of an integer is platform-dependent, although a maximum value of about two billion is the usual value (that's 32 bits signed). +64-bit platforms usually have a maximum value of about 9E18 + +**Warning** +If an invalid digit is given in an octal integer (i.e. 8 or 9), the rest of the number is ignored. + +### Floating point numbers + +Floating point numbers (also known as "floats", "doubles", or "real numbers") can be specified using any of the following syntaxes: + +```smarty +{var $a = 1.234} +{var $b = 1.2e3} +{var $c = 7E-10} +``` + +### Booleans + +This is the simplest type. A boolean expresses a truth value. It can be either TRUE or FALSE. +To specify a boolean literal, use the constants TRUE or FALSE. Both are case-insensitive. + + +```smarty +{set $a = true} +``` + +### NULL + +The special NULL value represents a variable with no value. NULL is the only possible value of type null. + +------ + + ### Variable operations Fenom supports math, logic, comparison, containment, test, concatenation operators... @@ -206,6 +365,97 @@ Floating point numbers (also known as "floats", "doubles", or "real numbers") ca {var $c = 7E-10} ``` +### Operators + +Fenom supports operators on values: + +* Arithmetic operators — `+`, `-`, `*`, `/`, `%` +* Logical operators — `||`, `&&`, `!$var`, `and`, `or`, `xor` +* Comparison operators — `>`, `>=`, `<`, `<=`, `==`, `!=`, `!==`, `<>` +* Bitwise operators — `|`, `&`, `^`, `~$var`, `>>`, `<<` +* Assignment operators — `=`, `+=`, `-=`, `*=`, `/=`, `%=`, `&=`, `|=`, `^=`, `>>=`, `<<=` +* String concatenation operators — `$str1 ~ $str2`, `$str1 ~~ $str2`, `$str1 ~= $str2` +* Ternary operators — `$a ? $b : $c`, `$a ! $b : $c`, `$a ?: $c`, `$a !: $c` +* Check operators — `$var?`, `$var!` +* Test operator — `is`, `is not` +* Containment operator — `in`, `not in` + +About [operators](./operators.md). + +## Arrays + +An array can be created using the `[]` language construct. It takes any number of comma-separated `key => value` pairs as arguments. +``` +[ + key => value, + key2 => value2, + key3 => value3, + ... +] +``` +The comma after the last array element is optional and can be omitted. +This is usually done for single-line arrays, i.e. `[1, 2]` is preferred over `[1, 2, ]`. +For multi-line arrays on the other hand the trailing comma is commonly used, as it allows easier addition of new elements at the end. + +```smarty +{set $array = [ + "foo" => "bar", + "bar" => "foo", +]} +``` + +The key can either be an integer or a string. The value can be of any type. + +Additionally the following key casts will occur: + +* Strings containing valid integers will be cast to the integer type. E.g. the key "8" will actually be stored under 8. + On the other hand "08" will not be cast, as it isn't a valid decimal integer. +* Floats are also cast to integers, which means that the fractional part will be truncated. + E.g. the key 8.7 will actually be stored under 8. +* Bools are cast to integers, too, i.e. the key true will actually be stored under 1 and the key false under 0. +* Null will be cast to the empty string, i.e. the key null will actually be stored under "". +* Arrays and objects can not be used as keys. Doing so will result in a warning: Illegal offset type. + +If multiple elements in the array declaration use the same key, only the last one will be used as all others are overwritten. + +An existing array can be modified by explicitly setting values in it. +This is done by assigning values to the array, specifying the key after dot or in brackets. +The key can also be omitted, resulting in an empty pair of brackets (`[]`). + +```smarty +{set $arr.key = value} +{set $arr[] = value} {* append value to end of array *} +``` + +If `$arr` doesn't exist yet, it will be created, so this is also an alternative way to create an array. +This practice is however discouraged because if `$arr` already contains some value (e.g. string from request variable) +then this value will stay in the place and `[]` may actually stand for string access operator. +It is always better to initialize variable by a direct assignment. + +## Constants + +A constant is an identifier (name) for a simple value in PHP. +As the name suggests, that value cannot change during the execution of the script. +A constant is case-sensitive by default. By convention, constant identifiers are always uppercase. + +## PHP functions and methods + +**TODO** + +```smarty +{$.php.some_function($a, $b, $c)} +``` + +```smarty +{$.php.MyClass::method($a, $b, $c)} +``` + + +```smarty +{$.php.My.NS.some_function($a, $b, $c)} +{$.php.My.NS.MyClass::method($a, $b, $c)} +``` + ## Modifiers @@ -229,63 +479,7 @@ These parameters follow the modifier name and are separated by a : (colon). ## Tags -Basically, tag seems like - -```smarty -{FUNCNAME attr1 = "val1" attr2 = $val2} -``` - -Tags starts with name and may have attributes - -Это общий формат функций, но могут быть исключения, например функция [{var}](./tags/var.md), использованная выше. - -```smarty -{include file="my.tpl"} -{var $foo=5} -{if $user.loggined} - Welcome, {$user.name}! -{else} - Who are you? -{/if} -``` - -В общем случае аргументы принимают любой формат переменных, в том числе результаты арифметических операций и модификаторов. - -```smarty -{funct arg=true} -{funct arg=5} -{funct arg=1.2} -{funct arg='string'} -{funct arg="string this {$var}"} -{funct arg=[1,2,34]} -{funct arg=$x} -{funct arg=$x.c} -``` - -```smarty -{funct arg="ivan"|upper} -{funct arg=$a.d.c|lower} -``` - -```smarty -{funct arg=1+2} -{funct arg=$a.d.c+4} -{funct arg=($a.d.c|count+4)/3} -``` - -## Static method support - -By default static methods are allowed in templates - -```smarty -{Lib\Math::multiple x=3 y=4} static method as tag -{Lib\Math::multiple(3,4)} inline static method -{12 + Lib\Math::multiple(3,4)} -{12 + 3|Lib\Math::multiple:4} static method as modifier -``` - -You may disable call static methods in template, see in [security options](./settings.md) option `deny_static` - +**TODO** ## Ignoring template code @@ -360,7 +554,7 @@ Tags to allow any number of spaces ### Tag options -TODO +**TODO** | name | code | type | description | | ------- | ---- | ----- | ------------ | diff --git a/docs/ru/operators.md b/docs/ru/operators.md index 6d6f402..e1b2c60 100644 --- a/docs/ru/operators.md +++ b/docs/ru/operators.md @@ -131,9 +131,9 @@ Fenom поддерживает префиксные и постфиксные о Оператор конкатенации `~` возвращает строку, представляющую собой соединение левого и правого аргумента. -`$a ~ $b` - возвращает результат объединения сток `$a` и `$b` -`$a ~~ $b` - возвращает результат объединения сток `$a` и `$b` через пробел -`$a ~= $b` - присвоение с объединением +* `$a ~ $b` - возвращает результат объединения сток `$a` и `$b` +* `$a ~~ $b` - возвращает результат объединения сток `$a` и `$b` через пробел +* `$a ~= $b` - присвоение с объединением ### Тернарные операторы diff --git a/docs/ru/readme.md b/docs/ru/readme.md index d947ad9..d725665 100644 --- a/docs/ru/readme.md +++ b/docs/ru/readme.md @@ -75,7 +75,7 @@ * [Операторы сравнения](./operators.md#Операторы-сравнения) — `>`, `>=`, `<`, `<=`, `==`, `!=`, `!==`, `<>` * [Битовые операторы](./operators.md#Битовые-операторы) — `|`, `&`, `^`, `~$var`, `>>`, `<<` * [Операторы присвоения](./operators.md#Операторы-присвоения) — `=`, `+=`, `-=`, `*=`, `/=`, `%=`, `&=`, `|=`, `^=`, `>>=`, `<<=` -* [Строковый оператор](./operators.md#Строковый-оператор) — `$str1 ~ $str2` +* [Строковые операторы](./operators.md#Строковые-операторы) — `$str1 ~ $str2`, `$str1 ~~ $str2`, `$str1 ~= $str2` * [Тернарные операторы](./operators.md#Тернарные-операторы) — `$a ? $b : $c`, `$a ! $b : $c`, `$a ?: $c`, `$a !: $c` * [Проверяющие операторы](./operators.md#Проверяющие-операторы) — `$var?`, `$var!` * [Оператор тестирования](./operators.md#Оператор-тестирования) — `is`, `is not` diff --git a/docs/ru/syntax.md b/docs/ru/syntax.md index 0265a23..bf725ab 100644 --- a/docs/ru/syntax.md +++ b/docs/ru/syntax.md @@ -188,17 +188,18 @@ ### Целые числа Целые числа могут быть указаны в десятичной (основание 10), шестнадцатеричной (основание 16), -восьмеричной (основание 8) или двоичной (основание 2) системе счисления, с необязательным предшествующим знаком (- или +). +восьмеричной (основание 8) или двоичной (основание 2) системе счисления, с необязательным предшествующим знаком (`-` или `+`). -Для записи в восьмеричной системе счисления, необходимо поставить пред числом 0 (ноль). Для записи в шестнадцатеричной системе счисления, необходимо поставить перед числом 0x. +Для записи в восьмеричной системе счисления, необходимо поставить пред числом 0 (ноль). +Для записи в шестнадцатеричной системе счисления, необходимо поставить перед числом 0x. Для записи в двоичной системе счисления, необходимо поставить перед числом 0b ```smarty -{var $a = 1234} // десятичное число -{var $a = -123} // отрицательное число -{var $a = 0123} // восьмеричное число (эквивалентно 83 в десятичной системе) -{var $a = 0x1A} // шестнадцатеричное число (эквивалентно 26 в десятичной системе) -{var $a = 0b11111111} // двоичное число (эквивалентно 255 в десятичной системе) +{var $a = 1234} десятичное число +{var $a = -123} отрицательное число +{var $a = 0123} восьмеричное число (эквивалентно 83 в десятичной системе) +{var $a = 0x1A} шестнадцатеричное число (эквивалентно 26 в десятичной системе) +{var $a = 0b11111111} двоичное число (эквивалентно 255 в десятичной системе) ``` **Замечение** @@ -227,7 +228,9 @@ Это простейший тип. Булевое выражает истинность значения. Он может быть либо TRUE либо FALSE. Для указания булевого значения, используйте ключевое слово TRUE или FALSE. Оба регистро-независимы. +```smarty {set $a = true} +``` ### NULL @@ -273,7 +276,6 @@ NULL - это отсутствие присутствия, а FALSE - прису "foo" => "bar", "bar" => "foo", ]} - ``` `key` может быть либо целым числом, либо строкой. `value` может быть любого типа.