Expressions

This article is a translation of article in russian.

Expressions in templates mostly used to substitute values of external parameters. However, there are some other possibilities.

Data Types

There are several data types of values which expressions does operate with.

string

Mostly used data type. When rendering in text flow, all HTML special characters will be encoded to corresponding entities. HTML code cannot be outputted with strings.

Strings can arrive from external parameters or can be created with string literals (see below).

boolean

Data type to check conditions. Nothing will be outputted both for true and for false, when outputted. This can be used for conditional rendering.

null

When you use undefined parameter, you will got a null value. Nothing will be outputted when rendering in text flow.

Predefined constants

There are following predefined constants: truefalse and null.

String literals

String literals can be enclosed wither in quotes "...", or apostrophes '...'. There is no special differense between strings in quotes and apostrophes.

There are some escape sequenses to use in string literals to insert specfic characters:

  • \n — line feed LF (0A);
  • \r — carriage return CR (0D);
  • \t — TAB (09);
  • \xHH — byte with specific ASCII code (exactly 2 hexadecimal digits);
  • \uHHHH — character with specific UNICODE code (exactly 4 hexadecimal digits), for example "\u2014" is MDASH "—";
  • \u{hex} — character with specific UNICODE code (any amount of hexadecimal digits), for example "\u{2014}" is MDASH "—";
  • \\ — backslash \ ;
  • \' — apostrophe ' ;
  • \" — quote " ;
  • \$ — dollar $ .

Another expression can be inserted into string literal with ${ }. For example:

<a
    href={ url }
    title={ "Title: ${ title }" }
    class={ "nav-link ${ active && "active" }" }
>
    ...
</a>

Operators

There are following operators to use in expressions in precedense order (high precedense first):

  1. (A) — group parentheses;
  2. !A — logical NOT;
  3. A && B — logical AND;
  4. A || B — logical OR;
  5. A ? B : C — conditional (ternary) operator.
!A

Result data type is boolean. Result value is logical inversion of operand.

A && B

Logical AND. If value of the left operand casts to false, then the result is the value of the left operand. Otherwise the result is the value of the right operand.

Similar behavior of the operator used in languages JavaScript and Perl.

A || B

Logical OR. If value of the left operand casts to true, then the result of the value of the left operand. Otherwise the result of the value of the right operand.

Similar behavior of the operator used in languages JavaScript and Perl.

A ? B : C

Conditional (ternary) operator. If the value of the expression A casts to true, then the result is the value of expression B. Otherwise the result is the value of expression C.

Nobody did vote for this article yet. Did this article help to you?