Built In Twig Functions
Twig comes with some built-in functions and filters that can be useful when creating view templates. The most common include:
Default Values
The |default
and |default("Default Value")
filters apply some default value when used with a null value. A common use case is safely accessing some variable that may not be defined.
Here's an example.
{% if some.nested.value.might.not.be.defined|default(false) %}
Array Filters
There are multiple useful built-in filters for working with arrays.
Vanilla Functions in Twig
Vanilla makes multiple useful framework functions available in templates. The code injecting these functions can be found here:
Checking Configuration
getConfig()
Check a configuration value.
Arguments
string $configName
- The key of the configuration value. Dot notation is supported.$defaultValue
- The default value if the config does not exist.
Usage
{% if getConfig('Garden.Some.Config', 'Default Value') %}
featureEnabled()
Check if a feature flag is enabled.
Arguments
string $featureFlagName
- The name of the feature flag.
Usage
{% if featureEnabled('DataDrivenTitleBar') %}
Translation & i18n
t() and getTranslation()
Both of these functions behave identically.
Arguments
string $translationKey
- The translation key to lookup. If no default is specified this will be used as the default.?string $defaultTranslation
- The default value to use if the translation cannot be found.
Usage
{{ t('Welcome') }}
{{ t('Welcome to the community.', 'Welcome to community. Check the different categories to explore.') }}
{{ getTranslation('Hello World') }}
sprintf
See the following resource.
Users and Permissions
hasPermission()
Check if a user has one of a set of permissions.
Arguments
string|array $permissions
- A single permission or an array of permissions.
Usage
{% if hasPermission('Garden.Settings.Manage') %}
{% elseif hasPermission(['Garden.Moderation.Manage', 'Garden.Community.Manage']) %}
{% endif %}
URLs
url()
Format a URL. Same as Vanilla's url()
function.
Arguments
string $path
- The path of the URL.bool $withDomain
- Whether or not to include the sites full domain in the URL.
Usage
// Default result - /categories.
// When in a subcommunity with the slug "/en" - /en/categories
// When on a node "/en" and a subcommunity "/product1" - /en/product1/categories
{{ url('/categories') }}
// Domain is https://mysite.com
// Default result - https://mysite.com/categories.
// When in a subcommunity with the slug "/en" - https://mysite.com/en/categories
// When on a node "/en" and a subcommunity "/product1" - https://mysite.com/en/product1/categories
{{ url('/categories', true) }}
assetUrl()
Format a URL of an asset. Similar to the url()
function but with slightly different behaviour.
Arguments
string $path
- The path of the asset.
Usage
// Domain is https://mysite.com
//
// Default result:
// https://mysite.com/themes/my-theme/design/image.jpg?v=2020.008-cbe1302
//
// When in a subcommunity with the slug "/en". (Note subcommunities don't affect these URLS.))
// https://mysite.com/themes/my-theme/design/image.jpg?v=2020.008-cbe1302
//
// When on a node "/en" and a subcommunity "/product1" - https://mysite.com/en/product1/categories
// https://mysite.com/en/themes/my-theme/design/image.jpg?v=2020.008-cbe1302
{{ assetUrl('/themes/my-theme/design/image.jpg') }}
sanitizeUrl()
Useful for sanitizing user generated URLs. It's possible a user could create an XSS by creating a URL with a javascript://
scheme. This method protects against that by stopping these URLs from executing.
Usage
<a href={{ sanitizeUrl(profile.meta.someUrl) }}>{{ profile.meta.someUrl }}</a>
// Input javascript://alert('XSS')
// Output unsafe://javascript://alert('XSS')
Events
Some views for Gdn_Controller
or Gdn_Module
may fire events. If refactoring one of these views in twig it may be necessary to fire some existing events. These methods can be used for that.
fireEchoEvent(
string $eventName, array &$args = [])
- Fires an event of a given name with an array of arguments to pass the result.
- Uses the exact event name given.
- Not a drop-in replacement for old view calls to
$this->fireEvent()
.
Fire an event using a fully qualified name. It is expected handlers of this event would use echo
to apply additional HTML content. That content will be captured and rendered into the view.
Usage
{{ fireEchoEvent('vanillaSettingsController_afterCategorySettings') }}
// With event arguments
{{ fireEchoEvent('vanillaSettingsController_afterCategorySettings', { form: Form }) }}
firePluggableEchoEvent(\
Gdn_Pluggable $pluggable, string $eventName, array &$args = [], string $fireAs = '')
Similar to fireEchoEvent()
. The different is this will fire off an existing Gdn_Pluggable
rather than the event manager.
- Fires an event using the given pluggable instance (complex event name resolution).
- Supports
fireAs
parameter from Gdn_Pluggable
. - Requires that the pluggable item be passed as a parameter (automatically injected into the template where available as
pluggable
) - Drop-in replacement for old view calls to
$this->fireEvent()
. - Example Usage
When refactoring this is often the event needed to preserve event compatibility.
Usage
// /views/vanilla/settings/editcategory.php
{{ firePluggableEchoEvent(pluggable, 'afterCategorySettings') }}
// With event args.
{{ firePluggableEchoEvent(pluggable, 'afterCategorySettings', { someArg: true }) }}