﻿# Special template syntax functions 

> [HTML Version](another-template-syntax-functions.html)

This article explains how to use additional functions in [template syntax](360027003711.md):

- [GenerateBarcode()](#barcode). Display a variable value as a barcode in a document.

- [JobPosition()](#jobposition). Insert a user’s job title.

- [PasteImage()](#pasteimage). Insert an image in place of a variable.

- [Hyperlink()](#hyperlink). Convert a value to a hyperlink.

- [ExtText()](#exttext). Create a custom function to extend document template capabilities. 

## The GenerateBarcode() function

The `GenerateBarcode()` function is used to encode a string from an app and insert it into a document as a barcode. For example, you can generate a barcode for a contract registration number or another unique document number. You can then use the barcode to match a paper document to its electronic copy.

BRIX connects to barcode scanning software through integration extensions. For more information, see [System extensions](360024498352.md) and the [BRIX public API documentation](https://api.elma365.com/ru/public-api/guides/IntroWebAPI/).

Barcode generation is available for file formats supported by Word and Excel.

**Syntax:**

`\{GenerateBarcode(\{\$variable\_code\}: string, barcode format, \[barcode height in pixels\])`,

Where:

- **Variable code**. The string value must meet the requirements of the format specified in the second argument.

- **Barcode format**. Supported barcode formats and string requirements:

	- **QR Code**. Any string. Supports resolutions up to 300 DPI. 

	- **EAN-8**. A string of up to eight digits, with the last digit used as a check digit.

	- **EAN-13**. A string of 12 digits, or 13 digits with the last used as a check digit.

You can also specify **EAN** without a specific type. In this case, the barcode type depends on the number of digits in the string.

- **Barcode height in pixels**. Optional. Choose a height based on the number of characters to ensure the barcode can be scanned correctly.

If you use the same string twice in a template to generate QR codes with different sizes, both QR codes will have the same size.

````
начало внимание

````
When using **EAN** formats, a check digit is added automatically if you do not provide one. Configure your barcode scanner to support these formats.

````
конец внимание

````
We recommend using **QR Code**, as it has fewer restrictions than **EAN**.

````
начало примера

````
Example

Consider the `\$numberstring = "5901234123457"` variable. This value works with **QR Code** and **EAN-13**. The format **EAN-8** cannot display this string because it requires eight digits.

1. `\{GenerateBarcode(\{\$numberstring\}, "QR Code", "125")\}.`

2. `\{GenerateBarcode(\{\$numberstring\}, "EAN-13", "125")\}`.

````
конец примера

## ````
The JobPosition() function

This function returns a user’s job title. 

**Syntax:**

`JobPosition(\{\$variable\_code\}: user, "format": string)`. 

Available format values: 

- `"first"`. Return the user’s first job title.

- `"all"`. Return all of the user’s job titles.

````
начало примера

````
Example

`\{JobPosition(\{\$\_\_createdBy\}, all)\}` —> returns all job titles for the user specified in the **Created by **field.

````
конец примера

## ````
The PasteImage() function

To insert an image into a document template from a context variable of type [Image](360009707032.md#image) and [Files](360009707032.md#file_type), use the `PasteImage() `function.

**Syntax:**

`PasteImage(\{\$variable\_code\}: image or file, width in pixels, height in pixels, crop instead of resize: true/false)`.

````
Начало примера

````
Examples

1. `\{PasteImage(\{\$image\})\}`. Insert an image at its original width and height from a variable of the **Image **type.

2. `\{PasteImage(\{\$file.\_\_id\})\}`. Insert an image at its original width and height from a variable of the **Files **type.

3. `\{PasteImage(\{\$image\}, 200)\}`. The image from a property of the **Image** type is displayed at a width of 200 pixels. The height adjusts to preserve the original aspect ratio.

4. `\{PasteImage(\{\$file.\_\_id\}, 200, 400)\}`. Resize the image from a property of the **Files** type to the specified dimensions.

5. `\{PasteImage(\{\$image\}, auto, 400)\}`. The image from a variable of the **Image** type is displayed at a height of 400 pixels. The width adjusts to preserve the original aspect ratio.

6. `\{PasteImage(\{\$file.\_\_id\}, 200, 400, true)\}`. Crop the image from a variable of the **Files** type to the specified dimensions without preserving the original aspect ratio.

````
Конец примера

### ````
Display multiple images

By default, the function `PasteImage()` inserts only one image or file into a document. To insert multiple images or files, use the function inside a [for loop](360027003711.md#cycle).

````
Начало примера

````
Example

Suppose you need to display a list of images in a document. The list is passed to the template variable `\{\$image\}` of the **Image (multiple) **type. The `for` loop applies the `PasteImage()` function repeatedly to insert all images from the list into the document in order.   
The loop requires two variables:

- `\{\$image\}`. Contains multiple images.

- `\{\$image1\}`. A temporary variable that holds each image in turn from `\{\$image\}`.

````
\{for image1 in \{\$image\}\}  
\{PasteImage(\{\$image1\}, 400, 200)\}  
\{end\}

````
After the loop finishes, the document contains the list of images. 

````
Конец примера

## ````
The Hyperlink() function

The `Hyperlink()` function is used in templates in the **.docx**, **.xls** and **.xlsx** formats to convert a value to a hyperlink. 

You can pass variables of the [String](360009707032.md#string) type from the app context as arguments or enter values manually. Use a full URL for the function to work correctly. 

**Syntax:**

1. `\{Hyperlink("URL", "Link text")\}`. Display clickable text that opens the specified website.

2. `\{Hyperlink("URL")\}`. Display the URL as a hyperlink.

````
начало примера

````
Examples using variables from the app context:

- `\{Hyperlink("\{\$site\}", "See official website")\}`. The website URL comes from a string in an app item, and the link text is entered manually.

- `\{Hyperlink ("https://brix365.com/", "\{\$\_\_name\}")\}`. The website URL is entered manually, and the link text comes from a field in an app item. 

````
конец примера

## ````
The ExtText() function 

If the built-in functions do not meet your template requirements, use the custom `ExtText()` function. It calls [API methods](extention-api.md) created in custom extensions and inserts their results into the document generated from the template.

**Syntax:**

`\{ExtText("Extension ID", "method address", additional argument: \{\$variable\_code\} or "string")\}`,

Where:

- **Extension ID**. Use the characters that follow **/ext\_** in the extension URL. For example, if the extension URL is **mycompany.brix365.com/admin/extensions/ext\_12ab-1212ab-12**, pass the value `"12ab-1212ab-12"`.

- **Method address**. Open the settings of the extension containing the method and go to the **API methods **tab. Find the method in the list and copy the value of the **Address **field.

- **Additional argument**. One or more arguments passed to the API method. Separate arguments with commas and list them in the required order. Enclose app properties in braces, for example, `\{\$app\_field\}`. Enclose other arguments in quotation marks, for example, `"function"`. In the API method script, the arguments are available under the keys **p1**, **p2** and so on, in the order they appear in the `ExtText() `function.

### Speed up custom function processing

For complex custom functions, you can change the processing mode to generate documents faster. Variables and functions are then processed in parallel instead of sequentially.

To do this, enable the `enableConcurrencyTemplateMapper` feature flag and set the number of parallel processing threads using the corresponding parameter in the configuration file. 

For more information, see [Modify BRIX parameters](change-settings-enterprise.md#enable-feature-flag-enterpeise). If you use SaaS Enterprise, contact your BRIX account manager to enable the feature flag.

### Example: a custom function for arithmetic operations

With an API method in a module and the `ExtText()` function, you can insert the results of arithmetic operations into a generated document: addition, subtraction, division, and multiplication. The function accepts numbers or app fields of the [Number](360009707032.md#number), [Money](360009707032.md#money), [String](360009707032.md#string) types containing a number. 

In this example, we will set up document generation from a template in the **Contracts **app. We will use a custom function to calculate and display the following values in a contract: 

- The total amount including a fixed delivery charge.

- The remaining balance after an advance payment.

- A penalty equal to twice the advance payment.

- The customer’s monthly payment when paying in installments over a specified number of months.

#### Step 1. Set up the app context

For this example, create the following properties in the **Contracts **app:

- **Contract amount** (`sum\_total`). A field of the **Money **type.

- **Advance payment** (`advance\_payment`). A field of the **Money **type.

- **Installment period** (`installment\_months`). A field of the **Number **type. On the contract page, the manager specifies the number of months over which the customer can pay the contract amount in installments.

#### Step 2. Create an API method in a module

All calculations run in an API method script. To set it up:

1. Go to **Administration > Extensions**. Create a custom module or open the settings of an existing one. Make sure the module is enabled.

2. Go to the **API methods** tab, open the method editor, and click **+ Add**.

3. Specify the method parameters:

- Name: **Perform calculation**.

- Address: select the `Get` method and enter `arithmetic`. You will use this value in the `ExtText() `function.

- Function name: `doArithmetic`.

4. Save the method settings.

For more information, see [API methods in modules](extention-api.md).

#### Step 3. Write the API method script

In the method editor, go to the tab **Scripts** and declare the `doArithmetic `function.

The script will be called during document generation by this function in the template: `\{ExtText("Extension ID", "method address", \{\$operand\_1\}, \{\$operand\_2\}, "operation")\}`. The function arguments are automatically passed to an object under the keys **p1**, **p2**, **p3**.

The script accepts arguments, converts variable values to numbers, and performs the selected arithmetic operation: addition: `add`, subtraction: `subtract`, multiplication: `multiply`, or division: `divide`.

Script for performing arithmetic operations via module API

````
  
async function doArithmetic(req: HttpApiRequest): Promise<HttpResponse | void> \{  
    console.log(\`Arithmentic function called\`);  
  
// Create the response object to return to the template  
    const resp = new HttpResponse();  
  
// Read the request body as a string. It contains the arguments passed to ExtText()  
    const bodystr = req.body\!.toString();  
    console.log(\`Raw query data: \$\{bodystr\}\`);  
  
// Parse the JSON string into an object to access the arguments  
    const parsed = JSON.parse(bodystr);  
  
// Helper function to convert a value to a number. Handles any numeric format from the template, such as a Money value or a decimal number   
    function parseNumber(value: any): number \{  
// Return numbers as they are. This also works for Money properties  
        if (typeof value === 'number') return value;  
  
// If the value is a string, replace the comma with a period and convert it to a number  
        if (typeof value === 'string') \{  
// Remove spaces and replace the comma with a period  
            const cleaned = value.replace(/\\s/g, '').replace(',', '.');  
            const result = Number(cleaned);  
            return result;  
        \}  
  
// Use standard conversion for all other types (boolean, null, undefined)  
        return Number(value);  
    \}  
  
// Extract arguments from the request. ExtText() arguments are passed as p1, p2, p3, etc., in the order they are listed  
    const a = parseNumber(parsed.p1); // first number (operand 1)  
    const b = parseNumber(parsed.p2); // second number (operand 2)  
    const operator = parsed.p3; // operation: "add", "subtract", "multiply", or "divide".  
    console.log(\`Parsing: a = \$\{a\} (\$\{typeof a\}), b = \$\{b\} (\$\{typeof b\}), operator = "\$\{operator\}"\`);  
  
// Check that both numbers are valid.  
    if (\!isFinite(a) || \!isFinite(b)) \{  
        const errorMsg = \`Error: invalid numbers (a=\$\{parsed.p1\}, b=\$\{parsed.p2\})\`;  
        console.log(errorMsg);  
        resp.status(200)  
            .content(errorMsg)  
            .set('Content-Type', 'text/html');  
        return resp;  
    \}  
  
// Perform the arithmetic operation specified by the operator  
    let result: string;  
     switch (operator) \{  
        case 'add':  
            result = String(a + b);  
            break;  
                   case 'subtract':  
            result = String(a - b);  
            break;             
                   case 'multiply':  
            result = String(a \* b);  
            break;  
                   case 'divide':  
// Check for division by zero to avoid an error  
            if (b === 0) \{  
                result = 'Error: division by zero\!';  
            \} else \{  
                result = String(a / b);  
            \}  
            break;  
                   default:  
// Report an error if the operator is unknown  
            result = \`Error: unknown operation "\$\{operator\}"\`;  
            break;  
    \}  
  
     console.log(\`Calculation result: \$\{result\}\`);  
  
// Build the HTTP response:  
 Status 200 indicates successful execution  
 Content-Type: text/html ensures the result is displayed correctly in the template  
 Pass the calculated result in the response body  
  
    resp  
        .status(200)  
        .content(result)  
        .set('Content-Type', 'text/html');  
  
     return resp;  
\}


````

#### ````
Step 4. Add ExtText() to the document template

In the contract template file, add calls to the `ExtText()` function for each operation. Specify the ID of the module you created, for example, `8ca92961-2c8a-418e-abff-7761a962265a`, the method address, for example, `arithmetic`, the app properties or a numeric argument, and the operation:

1. Addition: `\{ExtText("8ca92961-2c8a-418e-abff-7761a962265a", "arithmetic", \{\$sum\_total\}, "15 000", "add")\}`. Returns the total contract amount including a fixed delivery charge of 15,000.

2. Subtraction: `\{ExtText("8ca92961-2c8a-418e-abff-7761a962265a", "arithmetic", \{\$sum\_total\}, \{\$advance\_payment\}, "subtract")\}`. Returns the remaining balance after the advance payment.

3. Multiplication: `\{ExtText("8ca92961-2c8a-418e-abff-7761a962265a", "arithmetic", \{\$advance\_payment\}, "2", "multiply")\} `Returns the penalty for early termination of the contract, equal to twice the advance payment.

4. Division: `\{ExtText("8ca92961-2c8a-418e-abff-7761a962265a", "arithmetic", \{\$sum\_total\}, \{\$installment\_months\}, "divide")\} `Returns the monthly payment for the specified installment period.

For more information, see [Add and set up a document template](360026936731.md).

Suppose the contract page specifies a total amount of 500,000, an advance payment of 100,000, and an installment period of 4 months. The generated contract will contain these calculated values:

- Total amount: 515,000.

- Remaining balance: 400,000.

- Penalty: 200,000.

- Monthly payment: 125,000.