Craft Behaviors Reference
This page is the detailed reference for all yStore Twig functions. For a quick-reference overview with usage examples, see Twig Reference.
Craft CMS offers a flexible way to extend its core functionalities through behaviors, and our plugin leverages this capability to enhance Twig templates with custom methods and properties. By integrating custom behaviors, you can add new, dynamic functionalities to Twig, making it more powerful and tailored to your specific needs.
Product Functions
yuiProducts
Returns a new ProductQuery instance with customizable selection criteria.
Parameters:
- selectFields [Array] - A list of fields which need to be selected. If empty, all fields will be listed
- criteria [Object] - A list of criteria that will be applied on the query.
- orderBy [Object] - A list of order requirements. The default order is: ID DESC
{id: 3} - limit [Integer] - The limit how many rows the query should return. Leave empty or
nullto return all data - with [Object] - Its highly recommended that use this eager-loading functionality
You can find the usage example of this function in the Product Listing section.
getProduct
Fetches a product from an element that contains the configured Product field (typically an entry).
Parameters:
Element|null $element = null- The source element that holds the product field data.array $columns = []- Optional list of product columns to select.bool $cacheable = true- Enables/disables plugin-side product caching.
Usage
{% set product = craft.getProduct(entry) %}
{% if product %}
{{ product.getFinalPriceFormatted() }}
{% endif %}
getVariant
Fetches a product variant based on the specified criteria.
Parameters:
array $criteria = [](default: empty array)
getProductByVariantSku
Retrieves a product by its variant SKU.
getProductUrlById
Generates a product URL based on the product ID.
getYuiProductAddToAction
Generates an action URL to add a product to the cart.
Parameters:
Product $product(the product to be added)
getYuiClearCartAction
Generates an action URL to clear the cart.
Cart Functions
getCartItems
Returns the current items in the cart.
getCartTotals
Calculates and returns the totals for the items in the cart.
isAjaxCartEnabled
Checks if the AJAX cart functionality is enabled.
isAddToCartPopupEnabled
Checks if the add-to-cart popup is enabled.
isMinicartSidebarEnabled
Checks if the minicart sidebar is enabled.
isDemoNoticeEnabled
Checks if the demo notice is enabled.
Customer Functions
shopCustomerIsLoggedIn
Checks if a customer is currently logged in.
customerRegistrationPasswordIsRequired
Determines if a password is required for customer registration.
customerSubscriptionEnabled
Checks if customer subscription functionality is enabled.
customerWishlistEnabled
Checks if the customer wishlist functionality is enabled.
pluginFormValidationEnabled
Checks if form validation is enabled for the plugin.
getPluginFormValidationSiteKey
Retrieves the site key for plugin form validation.
renderPluginFormValidationTags
Renders the necessary tags for plugin form validation.
renderPluginFormValidationScripts
Renders the necessary scripts for plugin form validation.
Site Information Functions
getSiteCurrency
Retrieves the site’s currency, defaulting to 'EUR' if not specified.
Parameters:
string $default = 'EUR'(default: 'EUR')
getSiteCurrencySign
Retrieves the site’s currency sign, defaulting to '€' if not specified.
Parameters:
string $default = '€'(default: '€')
getSiteLanguage
Retrieves the site's default language.
getMaxSummaryItems
Gets the maximum number of summary items for sales checkout.
getTaxPriceDisplayType
Retrieves the tax price display type based on the given location.
Parameters:
string $location(the location to determine the tax display type)
getSearchEngine
Retrieves the default search engine configuration value.
canViewPrices
Determines if the current user can view prices.
isCatalogPricePermissionEnabled
Checks if catalog price permission is enabled.
getCountries
Returns a list of available countries.
Formatting Functions
formatAddress
Formats an address for display.
Parameters:
address(the address to be formatted)
getCssLink
Generates a <link> tag for a CSS file.
If a version parameter is provided, it appends the version number to the CSS file's URL as a query string, in the format (?version={version}), allowing for cache busting or specifying a particular version of the CSS file to ensure the browser loads the most recent or intended version of the stylesheets. This is particularly useful when deploying updates or managing multiple versions of assets across different environments.
Parameters:
string $filePath(the path to the CSS file)string $version(the version of the CSS file)
Avoid using random numbers or timestamps as the version value for CSS files, even in development mode. This practice prevents the browser from caching the CSS file properly because each version will appear unique (due to the changing random number or timestamp), causing the browser to treat it as a new resource with every request. Instead, use versioning based on actual updates (e.g., a version number or commit hash) to ensure proper caching while still allowing the browser to detect when a file has changed, improving performance and reducing unnecessary re-downloads of unchanged resources.
getCssStyleContent
The getCssStyleContent function retrieves the content of a CSS file and is optimized for performance by caching the content in production environments. This function is particularly useful for injecting critical CSS directly into your Twig templates, reducing the number of HTTP requests and improving the initial load time of your pages.
Parameters:
- cssSource [String] - The relative path to the CSS file in your project.
Usage Example:
To include inline CSS in your Twig template, you can use the getCssStyleContent function as follows:
<style title="Inline Styles">
{{ craft.getCssStyleContent('assets/css/critical/catalog')|raw }}
</style>
Best Practices
Minifying CSS:
Ensure that your CSS files are minified to reduce their size before deploying them to production. Smaller files will load faster and reduce the time needed to parse and apply styles.
Injecting Critical CSS:
Use this function within the {% head %} block in Twig to ensure that critical CSS is loaded early in the page rendering process.
This approach helps improve the perceived performance by styling the page as soon as possible.
{% block head %}
<style title="Inline Styles">
{{ craft.getCssStyleContent('assets/css/critical/contact')|raw }}
</style>
{% endblock %}
getJsContent
Retrieves the content of a JavaScript file.
Parameters:
string $cssSource(the source of the JavaScript file)
buildFilterQuery
Builds a filter query based on specified parameters.
buildParamsQuery
Builds a query string based on specified parameters.
buildRelatedToQuery
Builds a related-to query for fetching related entries.
getTotalLabels
Retrieves labels for totals based on the specified type.
Parameters:
string $type(the type of total label to retrieve)
getSectionData
Retrieves data for a specific section.
getAgreementLabel
Retrieves the label for an agreement.
renderFormToken
The renderFormToken function renders the CSRF token asynchronously, ensuring that it is always up-to-date and secure.
Usage Example:
{{ craft.renderFormToken()|raw }}
You must use the raw filter to render the token properly.
isMinifyEnabled
The isMinifyEnabled function returns true when the minification plugin is enabled.
We use the Minify Plugin from the Craft CMS store.
Usage Example:
{% if isMinifyEnabled() %}
{% minify %}
// Your code
{% endminify %}
{% endif %}
You can use this approach to minify inline CSS/JS codes as well, using the {% minify css %} or {% minify js %} wrappers.
This is only recommended if you do not already minify your CSS/JS by default.
Tax Functions
getTaxPercentById
Retrieves the tax percentage for a given tax category.
Parameters:
int $taxCategoryId(the ID of the tax category)bool $formatted = false(default: false, whether to format the percentage)
getYuiProductTaxCategoryLabel
Retrieves the tax category label for a product.
Parameters:
Product $product(the product to get the tax category label for)