Skip to content

Additional features Twig

Aleksey Ilyin edited this page Dec 3, 2024 · 12 revisions

Additional Twiп Functionы

currentUrl()

Description

Returns the current URL including the request URI.

Usage

{{ current_url() }}

parseUrl()

Description

Parses the current URL into an associative array containing scheme, host, path, query and fragment keys.

Usage

{% set parsed = parse_url(current_url()) %}
{{ parsed.scheme ~ '://' ~ parsed.host }}

pathFor($name, $data = [], $queryParams = [])

Description

Generates a URL for the given route name with optional data and query parameters.

Usage

{% set url = path_for('common:main') %}
<a href="{{ url }}">Main</a>

fullUrlFor(string $name, array $data = [], array $queryParams = []): string

Description

Generates a full URL for the given route name with optional data and query parameters.

Usage

{% set url = full_url_for('common:main') %}
<a href="{{ url }}">Main</a>

baseUrl()

Description

Returns the base URL without a trailing slash.

Usage

{{ base_url() }}

isCurrentPath($name, $data = [])

Description

Checks if the current path matches the given route name and data.

Usage

{% if is_current_path('product', {'id': 123}) %}
    <p>Current page is product with ID 123</p>
{% endif %}

currentPath($withQueryString = false)

Description

Returns the current path on given URI. If $withQueryString is true, includes the query string.

Usage

{{ current_path() }}

form($type, $name, $args = [])

Description

Generates a input using the specified type and name with optional arguments.

Usage

{{ form(type, name, {'class': ['form-control']}) }}

constant($reference, $value = null)

Description

Retrieves the value of a PHP constant by reference or returns a default value if it doesn't exist.

Usage

{% set types = constant('/App/Domain/Casts/Catalog/Attribute/Type::LIST') %}

pre(...$args): void

Description

Prints variables for debugging purposes.

Usage

{{ pre(user) }}

preg_replace($subject, $pattern, $replacement)

Description

Performs a regular expression replacement on the given subject string.

Usage

{% set text = "Hello, World!" %}
{% set result = preg_replace('/World/', 'Twig', text) %}
{{ result }}

count($obj)

Description

Counts the number of elements in an array or iterable object. Returns false for non-countable objects.

Usage

{% set arr = [1, 2, 3] %}
{{ count(arr) }}

df(mixed $obj = 'now', ?string $format = null): string

Description

Formats a date using the specified format. Default format is 'j-m-Y, H:i'.

Usage

{% set now = df() %}

dfm(?string $format = null): string

Description

Converts PHP date format to Moment.js format.

Usage

{{ dfm('Y-m-d') }}

collect(array|Collection $array = []): Collection

Description

Creates a new collection from an array or existing Collection.

Usage

{% set collection = collect([1, 2, 3]) %}

non_page_path(): string

Description

Returns the path without the current page number if present.

Usage

{{ non_page_path() }}

current_page_number(): int

Description

Returns the current page number from the URL path.

Usage

{{ current_page_number() }}

current_query(?string $key = null, mixed $value = null): string

Description

Returns the current query string or modifies it by setting a key-value pair.

Usage

{% set url = full_url_for('product', {'id': 123}) %}
{{ current_query('page', 2) }}

is_current_page_number($number): bool

Description

Checks if the current page number matches the given number.

Usage

{% if is_current_page_number(1) %}
    <p>This is page 1</p>
{% endif %}

build_query($url = '', array $params = []): string

Description

Builds a query string from an optional URL and parameters array.

Usage

{% set url = 'https://example.com' %}
{% set params = {'q': 'search', 'page': 1} %}
{{ build_query(url, params) }}

base64_encode(string $string): string

Description

Encodes a string using Base64 encoding.

Usage

{{ base64_encode('Hello, Twig!') }}

base64_decode(string $string, bool $strict = false): false|string

Description

Decodes a Base64-encoded string. Optional strict flag controls the behavior on invalid input.

Usage

{% set encoded = 'SGVsbG8sIFdvcmxkIQ==' %}
{{ base64_decode(encoded) }}

json_encode($value, int $flags = JSON_UNESCAPED_UNICODE, int $depth = 512): false|string

Description

Encodes a PHP value into JSON format.

Usage

{% set obj = {'name': 'John', 'age': 30} %}
{{ json_encode(obj) }}

json_decode(string $json, ?bool $associative = true, int $depth = 512, int $flags = 0): mixed

Description

Decodes a JSON string into a PHP value.

Usage

{% set json = '{"name": "John", "age": 30}' %}
{{ json_decode(json) }}

cache_put(string $key, mixed $value, int $seconds, string $type = 'memory'): void

cache_get(string $key, mixed $default = null, string $type = 'memory'): mixed

Description

Cache management functions for Twig extension.

Usage

cache_put('my_key', 'Hello, Twig!', 3600)

convert_size(int $size): string

Description

Converts a file size to human-readable format (e.g., KB, MB).

Usage

{{ convert_size(2048) }}

qr_code(mixed $value, $size = 256, $margin = 0): string

Description

Generates a QR code image for the given value with optional size and margin.

Usage

{{ qr_code('https://example.com') }}

file(array $criteria = [], $order = ['date' => 'desc'], $limit = 10, $offset = null)

Description

Fetches files based on criteria, order, limit and offset. Uses FileService.

Usage

{% set files = file({'ext': 'webp'}, ['date' => 'desc']) %}

page(array $criteria = [], $order = ['date' => 'desc'], $limit = 10, $offset = null)

Description

Fetches pages based on criteria, order, limit and offset. Uses PageService.

Usage

{% set pages = page({'title': 'The Hitchhiker's Guide to the Galaxy'}) %}

publication_category(bool $public = true)

Description

Fetches publication categories based on public status (optional).

Usage

{% set category = publication_category(true) %}

publication(array $criteria = [], $order = [], $limit = 10, $offset = null)

Description

Fetches publications based on criteria, order, limit and offset. Uses PublicationService.

Usage

{% set publications = publication([], ['date' => 'desc']) %}

reference(?string $type = null, bool $pluck = false)

Description

Fetches references by type or all types (if null). Optional pluck feature returns a collection of key-value pairs.

Usage

{% set length_class = reference(ReferenceType::LENGTH_CLASS) %}

parameter(mixed $name = null, mixed $default = null): mixed

Description

Returns the value of a named configuration parameter or default value (if provided).

Usage

{{ parameter('common_homepage') }}

guestbook($order = ['date' => 'desc'], $limit = 10, $offset = null)

Description

Fetches guest book rows based on order, limit and offset. Uses GuestBookService.

Usage

{% set guestbooks = guestbook(['date' => 'asc']) %}

catalog_attribute(array $criteria = [], $order = [])

Description

Fetches catalog attributes based on criteria and optional order. Uses CatalogAttributeService.

Usage

{% set attributes = catalog_attribute() %}

catalog_category(array $criteria = [], $order = ['order' => 'asc'])

Description

Fetches catalog categories based on criteria and optional order. Uses CatalogCategoryService.

Usage

{% set categories = catalog_category() %}

catalog_product(array $criteria = [], $order = ['order' => 'asc'], $limit = 10, $offset = null)

Description

Fetches catalog products based on criteria, order, limit and offset. Uses CatalogProductService.

Usage

{% set products = catalog_product() %}

catalog_product_price_type($context)

Description

Returns the product price type based on user context.

Usage

{% set priceType = catalog_product_price_type() %}

catalog_product_popular(int $limit = 10, string $type = \App\Domain\Casts\Catalog\Product\Type::PRODUCT): Collection

Description

Fetches popular products by count of orders. Uses CatalogOrderProduct database query.

Usage

{% set popularProducts = catalog_product_popular() %}

catalog_product_view(string $uuid = null, int $limit = 10)

Description

Saves or returns the list of viewed product UUIDs in session.

Usage

{% set viewedProducts = catalog_product_view('UUID') %}

catalog_product_dimensional_weight($context, $product = null): float

Description

Calculates the dimensional weight of a product based on its dimensions and configuration constants.

Usage

{{ catalog_product_dimensional_weight([product = null]) }}

catalog_order(array $criteria = [], $order = ['date' => 'desc'], $limit = 10, $offset = null)

Description

Fetches catalog orders based on criteria, order, limit and offset. Uses CatalogOrderService.

Usage

{% set orders = catalog_order() %}

user(array $criteria = [], $order = ['email' => 'asc'])

Description

Fetches users based on criteria and optional order. Uses UserService.

Usage

{% set users = user() %}

user_group(array $criteria = [], $order = ['title' => 'asc'])

Description

Fetches user groups based on criteria and optional order. Uses UserGroupService.

Usage

{% set userGroups = user_group() %}

Clone this wiki locally